Home » excel » vba – Define Cell Location Variable in Excel

vba – Define Cell Location Variable in Excel

Posted by: admin May 14, 2020 Leave a comment

Questions:

I’m looking for a way to, instead of typing “ActiveCell.OffSet(1,1) over and over again in my vba code, define that as a variable, “x” and use that instead.

I have to use the dim command to do this but I”m not sure what the data type would be.

Suggestions?

When I test it using the code below I get Runtime Error 1004.

Private Sub CommandButton1_Click()
    Dim i As Range
    Set i = ActiveCell

     ActiveSheet.Range(ActiveSheet.Range(i), ActiveSheet.Range(i).End(xlUp)).Select

End Sub
How to&Answers:

In response to your edit

Avoid the use of .Select/Activate and fully qualify your objects. INTERESTING READ

Your code can be written as

Private Sub CommandButton1_Click()
    Dim ws As Worksheet
    Dim rng1 As Range, rng2 As Range

    '~~> Change as applicable
    Set ws = ThisWorkbook.Sheets("Sheet1")

    With ws
        Set rng1 = ws.Range("A10")

        Set rng2 = .Range(rng1, rng1.End(xlUp))

        With rng2
            Debug.Print .Address
            '
            '~~> Do something with the range
            '
        End With
    End With
End Sub

If you still want to know what was wrong with your code then see this.

You have already defined your range. You do not need to add ActiveSheet.Range() again. Your code can be written as

Private Sub CommandButton1_Click()
    Dim i As Range

    Set i = ActiveCell

    ActiveSheet.Range(i, i.End(xlUp)).Select
End Sub

EDIT

Followup from comments

Was ActiveSheet.Range() actually problematic or just redundant? – user3033634 14 mins ago

It is problematic. The default property of a range object is .Value

Consider this example which will explain what went wrong with your code

Sub Sample()
    Dim ws As Worksheet
    Dim rng As Range

    Set ws = ThisWorkbook.Sheets("Sheet1")

    With ws
        Set rng = .Range("A1")

        rng.Value = "Blah"

        MsgBox rng           '<~~ This will give you "Blah"
        MsgBox rng.Value     '<~~ This will give you "Blah"
        MsgBox rng.Address   '<~~ This will give you "$A$1"

        MsgBox ws.Range(rng) '<~~ This will give you an error
        '~~> Why? Becuase the above is evaluated to
        'MsgBox ws.Range("Blah")

        MsgBox ws.Range(rng.Address) '<~~ This will give you "Blah"
    End With
End Sub

Answer:

Dim x As Range
Set x = ActiveCell.OffSet(1,1)

EDIT: in response to your comment:

Private Sub CommandButton1_Click()
    Dim i As Range

    Set i = ActiveCell

    ActiveSheet.Range(i, i.End(xlUp)).Select
End Sub