Range is one of the most important and most commonly used Excel VBA object.
In fact, we have dealt with the Range object in previous lessons. Range has many methods and proeprties, we will examine a few of them here.
19.1 The Select Method
The Range object contains two arguments that specifies a selected area on the spreadsheet. The syntax is
Range(starting_cell,Ending_ Cell)
For example, Range("A1:C6") means the specified range is from cell A1 to C6.
To select the specified range, the syntax is
Range("A1:C6").Select
where select is a method of the Range object
Example 19.1
Private Sub CommandButton1_Click()
Range("A1:C6").Select
End Sub
19.2 The Columns Property
The columns property of the Range object is to select a certain columns in the particular range specified by the Range object.
The syntax is
This example select column C in the range A1 to C6
Private Sub CommandButton2_Click()
Range("A1:C6").Columns(3).Select
End Sub
You may also use Cells(1,1) to Cells(6,3) instead of A1:C6, the syntax is
Range(Cells(1,1),Cells(6,3)).Columns(3).Select
The output is as shown in Figure 19.1
19.3 Using With Range...End With
You can also format font the cells in a particular column in terms of type, color, bold,italic, underlined and size using the With Range...End With Structure. It can also be used to format other Range properties like background color. Using With Range....End With structure can save time and make the code leaner.
Example 19.3
Private Sub CommandButton1_Click()
With Range("A1:C6").Columns(2)
.Font.ColorIndex = 3
.Font.Bold = True
.Font.Italic = True
.Font.Underline = True
.Font.Name = "Times New Roman"
.Font.Size = 14
.Interior.Color = RGB(255, 255, 0)
End With
End Sub
* Without using With Range...End With, you need to write every line in full, like this
Range("A1:C6").Columns(2).Font.ColorIndex = 3
Figure 19.2
19.4 The Rows Property
Basically the syntax for the Rows property is similar to that of the Columns property, you just need to replace Columns with rows.
The syntax of selecting a row within a certain range is
Range(starting_cell,Ending_ Cell).Rows(i).Select
Example 19.4
This following code selects the third row within the range A1 to F3
Private Sub CommandButton2_Click()
Range("A1:F3").Rows(3).Select
End Sub