建立範圍
一個範圍無法建立或填充以同樣的方式字串將:
Sub RangeTest()
Dim s As String
Dim r As Range 'Specific Type of Object, with members like Address, WrapText, AutoFill, etc.
' This is how we fill a String:
s = "Hello World!"
' But we cannot do this for a Range:
r = Range("A1") '//Run. Err.: 91 Object variable or With block variable not set//
' We have to use the Object approach, using keyword Set:
Set r = Range("A1")
End Sub
將引用限定為最佳實踐,因此從現在開始,我們將在此處使用相同的方法。
有關在 MSDN 上建立物件變數(例如 Range)的更多資訊。有關 MSDN 上的 Set 語句的更多資訊。
有不同的方法來建立相同的範圍:
Sub SetRangeVariable()
Dim ws As Worksheet
Dim r As Range
Set ws = ThisWorkbook.Worksheets(1) ' The first Worksheet in Workbook with this code in it
' These are all equivalent:
Set r = ws.Range("A2")
Set r = ws.Range("A" & 2)
Set r = ws.Cells(2, 1) ' The cell in row number 2, column number 1
Set r = ws.[A2] 'Shorthand notation of Range.
Set r = Range("NamedRangeInA2") 'If the cell A2 is named NamedRangeInA2. Note, that this is Sheet independent.
Set r = ws.Range("A1").Offset(1, 0) ' The cell that is 1 row and 0 columns away from A1
Set r = ws.Range("A1").Cells(2,1) ' Similar to Offset. You can "go outside" the original Range.
Set r = ws.Range("A1:A5").Cells(2) 'Second cell in bigger Range.
Set r = ws.Range("A1:A5").Item(2) 'Second cell in bigger Range.
Set r = ws.Range("A1:A5")(2) 'Second cell in bigger Range.
End Sub
在示例中注意,單元格(2,1)等效於範圍(A2
)。這是因為 Cells 返回一個 Range 物件。
一些訊息來源: 範圍內的 Chip Pearson-Cells ; MSDN 範圍物件 ; John Walkenback - 參考你的 VBA 程式碼中的範圍 。
另請注意,在範圍宣告中使用數字的任何例項中,數字本身都在引號之外,例如 Range(A
和 2),你可以將該數字替換為包含範圍的變數整數/長。例如:
Sub RangeIteration()
Dim wb As Workbook, ws As Worksheet
Dim r As Range
Set wb = ThisWorkbook
Set ws = wb.Worksheets(1)
For i = 1 To 10
Set r = ws.Range("A" & i)
' When i = 1, the result will be Range("A1")
' When i = 2, the result will be Range("A2")
' etc.
' Proof:
Debug.Print r.Address
Next i
End Sub
如果你使用雙迴圈,單元格更好:
Sub RangeIteration2()
Dim wb As Workbook, ws As Worksheet
Dim r As Range
Set wb = ThisWorkbook
Set ws = wb.Worksheets(1)
For i = 1 To 10
For j = 1 To 10
Set r = ws.Cells(i, j)
' When i = 1 and j = 1, the result will be Range("A1")
' When i = 2 and j = 1, the result will be Range("A2")
' When i = 1 and j = 2, the result will be Range("B1")
' etc.
' Proof:
Debug.Print r.Address
Next j
Next i
End Sub