我有两个范围,每个范围都包含一个单元格(例如“A1”和“C3”)。
如何获得一个包含这两者之间所有单元格的新范围(“A1:C3”)?
我试过这个:
Set NewRange = Range(Range1.Address:Range2.Address)
另外如何设置 R1C1 格式的范围?我想使用 Range("R1C2") 之类的东西,而不是 Range("A2")。
像这样?
Sub Sample()
Dim rng1 As Range, rng2 As Range
Dim NewRng As Range
With ThisWorkbook.Sheets("Sheet1")
Set rng1 = .Range("A1")
Set rng2 = .Range("C3")
Set NewRng = .Range(rng1.Address & ":" & rng2.Address)
Debug.Print NewRng.Address
End With
End Sub
代替 R1C1 格式使用Cells(r,c)
. 这会给你更多的灵活性+控制
所以Range("A2")
可以写成Cells(2,1)
您可以通过各种方式设置新范围。下面是几个例子。要获得 R1C1 格式 - 我个人发现输入普通公式然后使用 VBA 提取所需的 R1C1 格式更容易。请参阅下面的 debug.print 语句。
Sub test()
Dim rng1 As Range
Dim rng2 As Range
Dim newRng As Range
With Sheet1
Set rng1 = .Range("A1")
Set rng2 = .Range("C3")
Debug.Print rng1.FormulaR1C1
Debug.Print rng1.FormulaR1C1Local
'Method1
Set newRng = .Range(rng1, rng2)
'method2
Set newRng = .Range(rng1.Address, rng2.Address)
'method3 (Only works if rng1 & rng2 are single cells
Set newRng = .Range(rng1.Address & ":" & rng2.Address)
'method4
Set newRng = Union(rng1, rng2)
End With
End Sub
当范围不相邻时,方法 4 与方法 1 不同。
With Sheet1
Set rng1 = .Range("A1:A3")
Set rng2 = .Range("C1:C3")
'This combines the two separate ranges, so select A1, A2, A3, C1, C2, C3
set newRng = Union(rng1, rng2)
'This combines the two ranges in the same way as when using "A1:C3",
'so including the cells from column B
set newRng = .Range(rng1, rng2)
也可能是这样的:
Dim newRange as Range
Set newRange = Range("A1:A4,A7:A9,C1:D9") 'Three different regions grouped
'or
Set newRange = Range("A1:A4,A7:A9,C1:D9, D10:D11") 'Four different regions grouped.
'or
Set newRange = Range("A1:A4,A7:A9,C1:D9, D10:D11, ...") 'N different regions grouped.
把它放在一个模块中:
Private Function CombineRanges(rng1 As Range, rng2 As Range) As Range
Set CombineRanges = ActiveSheet.Range(rng1.Address & ":" & rng2.Address)
End Function
像这样使用它:
Dim NewRange As Range
Set NewRange = CombineRanges(Range1, Range2)