1

我有以下代码:

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 所以有 microsoft office object library 15?谢谢

4

1 回答 1

1

当我离开工作表时,我遇到了问题

是的。您没有完全限定对象

试试这个(未经测试)

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
于 2013-09-13T12:03:18.163 回答