24

我有两个范围,每个范围都包含一个单元格(例如“A1”和“C3”)。

如何获得一个包含这两者之间所有单元格的新范围(“A1:C3”)?

我试过这个:

Set NewRange = Range(Range1.Address:Range2.Address)

另外如何设置 R1C1 格式的范围?我想使用 Range("R1C2") 之类的东西,而不是 Range("A2")。

4

5 回答 5

28

像这样?

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)

于 2012-09-21T09:31:16.527 回答
16

您可以通过各种方式设置新范围。下面是几个例子。要获得 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
于 2012-09-21T09:31:59.453 回答
14

当范围不相邻时,方法 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)
于 2014-04-01T10:32:40.717 回答
2

也可能是这样的:

    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.
于 2017-02-11T00:35:12.170 回答
2

把它放在一个模块中:

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)
于 2017-09-12T10:56:26.373 回答