How to create a range from two ranges in VBA?

前端 未结 5 739
北恋
北恋 2020-11-29 09:15

I have two ranges, each containing a single cell (for example \"A1\" and \"C3\").

How do I get a new range containing all the cells between these two (\"A1:C3\")?

5条回答
  •  离开以前
    2020-11-29 09:47

    You can set the a new range in various ways. Below are a few examples. To get R1C1 format - I personally find it easier entering the normal formula and then using VBA to extract the R1C1 format required. See the debug.print statements below.

    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
    

提交回复
热议问题