运行时错误'1004'定义变量和对象错误

时间:2013-09-13 11:57:54

标签: excel-vba vba excel

我有以下代码:

sub test()
list1 = Sheets(1).Range("a2", Range("a2").End(xlDown)).Rows.Count
list2 = Sheets(2).Range("a2", Range("a2").End(xlDown)).Rows.Count

MsgBox list1
MsgBox list2
end sub

当我离开工作表时,我有问题,我已经创建了一个解决方案:

Sub tester()

Dim list1 As Range

With ActiveWorkbook

Set list1 = .Worksheets("Sheet1").Range("a2")
Set list1 = Range(list1, list1.End(xlDown))
MsgBox list1.Rows.Count

End With
End Sub

上面是list1的一个例子,但这似乎有点过分了。我做错了什么,我有一些设置,没有激活的参考,或什么?我有excel2013所以微软Office对象库15 ??谢谢

1 个答案:

答案 0 :(得分:1)

  

当我离开工作表时,我有问题

是。您没有完全限定对象

试试这个(UNTESTED)

Sub test()
    list1 = Sheets(1).Range("a2", Sheets(1).Range("a2").End(xlDown)).Rows.Count
    list2 = Sheets(2).Range("a2", Sheets(1).Range("a2").End(xlDown)).Rows.Count

    MsgBox list1
    MsgBox list2
End Sub

话虽如此,我首选的工作方式是声明对象,然后使用它们

所以上面的代码可以写成(UNTESTED)

Sub test()
    Dim wb As Workbook
    Dim ws1 As Worksheet, ws2 As Worksheet
    Dim list1 As Long, List2 As Long

    Set wb = ThisWorkbook

    Set ws1 = wb.Sheets(1)
    Set ws2 = wb.Sheets(2)

    list1 = ws1.Range("A2", ws1.Range("a2").End(xlDown)).Rows.Count
    List2 = ws2.Range("a2", ws2.Range("a2").End(xlDown)).Rows.Count

    MsgBox list1
    MsgBox List2
End Sub