创建范围
一个范围无法创建或填充以同样的方式字符串将:
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