在Excel中定义单元格位置变量

时间:2013-11-27 19:54:30

标签: excel vba

我正在寻找一种方法,而不是在我的vba代码中一遍又一遍地输入“ActiveCell.OffSet(1,1)”,将其定义为变量“x”并改为使用它。

我必须使用dim命令来执行此操作,但我不确定数据类型是什么。

建议?

当我使用下面的代码测试它时,我得到运行时错误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

2 个答案:

答案 0 :(得分:3)

回应你的编辑

避免使用.Select/Activate并完全限定您的对象。 INTERESTING READ

您的代码可以写成

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

如果你仍然想知道你的代码有什么问题,那就看看吧。

您已经定义了范围。您无需再次添加ActiveSheet.Range()。您的代码可以写成

Private Sub CommandButton1_Click()
    Dim i As Range

    Set i = ActiveCell

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

修改

评论后续跟进

  

ActiveSheet.Range()实际上是有问题还是多余? - user3033634 14分钟前

problematic。范围对象的默认属性是.Value

考虑这个例子,它将解释你的代码出了什么问题

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

答案 1 :(得分:0)

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

编辑:回应你的评论:

Private Sub CommandButton1_Click()
    Dim i As Range
    Set i = ActiveCell
    ActiveSheet.Range(i, i.End(xlUp)).Select
End Sub