VBA in Excel

Selection

One of the first things you will want to know how to do is select cells and apply formatting/text to them. Fortunately, this is very simple.

If you want to select a cell on a spreadsheet, you can use the Range object. This object is very useful. It 'points' to whatever cell or cells you specify, and then lets you perform an action (ie selecting it, or applying formatting). You pass the same cell references as you do in the rest Excel (ie C3). So, to select B4, you use this code:

Range("B4").Select

If you want to select more than one cell, you pass a range of cells. To do this, you specify the top left hand corner cell, and the bottom right hand corner cell, with a : in-between. For example, to select B6 to D8 (ie from B6, 3 cells down, 3 cells across), you simply use this code:

Range("B6:D8").Select

Obviously, if you are using Loops to add or select lots of cells, you won't want to have to generate the column letters. Instead, Excel also provides a Cells object, which instead of accepting "B6", it accepts 6,2, ie Row,ColumnNumber. So,

Cells(4,2).Select

does the same as

Range("B4").Select

Once you have selected cells, you will probably want to refer to them, and to do this, you use the ActiveCell (to refer to one cell... in a selection, it is the cell that is white), or Selection to refer to a group of cells.

Single cell selection

Multiple selection

So,

Msgbox ActiveCell.Value

displays a message box containing the value of the active cell, and

Selection.Font.Bold = True

makes all the text in the selection bold. More on formatting in the next section...

You might also like...

Comments

About the author

James Crowley

James Crowley United Kingdom

James first started this website when learning Visual Basic back in 1999 whilst studying his GCSEs. The site grew steadily over the years while being run as a hobby - to a regular monthly audien...

Interested in writing for us? Find out more.

Contribute

Why not write for us? Or you could submit an event or a user group in your area. Alternatively just tell us what you think!

Our tools

We've got automatic conversion tools to convert C# to VB.NET, VB.NET to C#. Also you can compress javascript and compress css and generate sql connection strings.

“Never trust a programmer in a suit.” - Anonymous