Friday, 17 February 2017

excel vba - How to create a range from 2 ranges in VBA



I have two ranges each containig a single cell (for example "A1" and "C3")



What is the easiest way to get a new range containing all the cells between these two ("A1:C3").



I am trying to write something like this, but this doesn't work:



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



Another question I have is how to set a range in R1C1 format? I want to use something like Range("R1C2") instead of Range("A2").



Thanks!


Answer



Like this?



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


Instead of R1C1 format use Cells(r,c). That will give you more flexibility + control



So Range("A2") can be written as Cells(2,1)


No comments:

Post a Comment

c++ - Does curly brackets matter for empty constructor?

Those brackets declare an empty, inline constructor. In that case, with them, the constructor does exist, it merely does nothing more than t...