4

I am trying to use Excel VBA to create a Range variable that is one column to the right of sourcerange.

Dim targetRange as Range
Dim sourcerange as range

Set sourceRange = range("B1:B2") 'Works

Set targetRange = Range(cells(sourceRange.row, sourceRange.Column + 1)) 'does not work

Set targetRange = Range(Cells(2, 2)) 'does not work

Can anyone help explain why it is not working?

3 Answers 3

5

Use

Sub Demo()
    Dim targetRange As Range, sourcerange As Range
    Set sourcerange = Range("B1:B2") 'Works
    Set targetRange = sourcerange.Offset(0, 1)
    Debug.Print targetRange.Address
End Sub
Sign up to request clarification or add additional context in comments.

6 Comments

Well that was a quite a bit simpler than my suggestion. Clever thinking :-)
Note that Set sourcerange = Range("B1:B2") will always be referring to the activesheet.
Or just use a single line (with an explicit sheet reference): Set targetRange = Activesheet.Range("B1:B2").Offset(0, 1)
@ThunderFrame - I just tried to modify the line where OP was not able to get the desired result. But you are right, this will refer to activesheet and can be written in a single line as mentioned by you.
@Mrig The volatile nature of the worksheet function matters when used in a formula, but why do you think it matters in the VBA? It's a method being explicitly called against a Range object, not as a worksheet function.
|
0

Did you mean something like this?

Dim sourceColumn As Long
Dim firstRow As Long
Dim lastRow As Long
Dim sourceRange As Range
Dim targetRange As Range

'Set source column number, and first + last row
sourceColumn = 2
firstRow = 1
lastRow = 3

'Set the source range, using the variables
Set sourceRange = Range(Cells(firstRow, sourceColumn), Cells(lastRow, sourceColumn))

'Likewise, set the target range, but using column number + 1
Set targetRange = Range(Cells(firstRow, sourceColumn + 1), Cells(lastRow, sourceColumn + 1))

2 Comments

Might want some error handling for when the sourceRange refers to the last column.
I agree that this is a slightly over-simplified example. It might also be worth to specify which workbook and sheet to use. It was primarily thought as a concept, which works in the simpler cases :-)
0

You have to always refer to the sheet the range owns to and even if the range contains only one cell, setting a starting and an ending cell.

Set targetRange = YourSheet.Range(YourSheet.Cells(sourceRange.row, sourceRange.Column),YourSheet.Cells(sourceRange.row, sourceRange.Column+1))

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.