Friday, September 6, 2013

How to Use the CELLS() Object in Excel VBA

When you're coding in Excel VBA, you will use the CELLS() object all the time. Why? Because it allow you flexibility. You can have a Dynamic - ever changing row or column and use the same variable.

Here's how it works:
You type "Cells" and put a parentheses. Put the row number you want, a comma, then the column number, end parenthesis. Simple.

Before this sounds too complicated, let's just try it.

1. Open Excel and hit Alt + F11. This opens Visual Basic Editor.
2. Make a new Module by clicking the dropdown as pictured below:









2. Copy and paste this code:
Sub MyCellsMacro()

Cells(1,1) = 100

End Sub


To run this macro, just click within the area of the macro and hit F5.
You'll see that it put the number 100 in cell A1 just as if you'd typed it there.
















Watch the Video!!
If you want cell F2, then you need to think in terms of row 2, column F or number 6.
Type Cells(2,6) = "hello" and run that! It will put the word hello in cell F2.

ALTERNATE METHOD:
You may also type in the column letter surrounded by quotes. Example:
Cells(2,"F") = "hello"

TO RUN YOUR NEW MACRO:
Just hit Alt+F8 and select your new macro, called MyFirstMacro, and double click or hit 'Run'.

Check out My Youtube Excel VBA Course - FREE.
www.youtube.com/user/ExcelVbaIsFun

1 comment:

  1. Pretty good post. I just stumbled upon your blog and wanted to say that I have really enjoyed reading your blog posts. Any way I'll be subscribing to your feed and I hope you post again soon. Big thanks for the useful info.
    visual basic course london

    ReplyDelete