Saturday, September 19, 2015

How to Use Cell in Excel VBA

Worksheet.cells property returns a Range object that represents all the cells on the worksheet (not just the cells that are currently in use).
Because the Item property is the default property for the Range object, you can specify the row and column index immediately after the Cells keyword.
Example of using cells:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
Sub Sample1()
Dim i As Integer

For i = 1 To 10
    Worksheets("Sheet1").Cells(i, 1).Font.Size = 12
    Worksheets("Sheet1").Cells(i, 1).Offset(0, 1).Value = Worksheets("Sheet1").Cells(i, 1).Value
    Worksheets("Sheet1").Cells(i, 1).Offset(0, 1).Font.Size = 12 + i
Next i

End Sub

This example clears the formula in cell one on Sheet1.

1
2
3
4
5
Sub Sample2()

Worksheets("Sheet1").Cells(1).ClearContents

End Sub

This example sets the font and font size for every cell on Sheet1 to 8-point Arial


1
2
3
4
5
6
7
8
Sub Sample3()

With Worksheets("Sheet1").Cells.Font
    .Name = "Arial"
    .Size = 8
End With

End Sub

Download example file

No comments :

Post a Comment