从个人宏访问两个不同的工作簿

时间:2018-12-12 16:38:16

标签: excel vba excel-vba

我有一个个人宏,可以访问两个不同的工作簿。

这是更新的代码:

Sub Copy_and_Paste()
    Dim ws1 As Worksheet Set ws1 = Workbooks("Submittals").Worksheets("Sheet1") 
    Dim ws2 As Worksheet Set ws2 = Workbooks("Previous").Worksheets("Sheet1") 
    Dim num_rows_A As Integer
    Dim num_rows_B As Integer

    num_rows = ws1.Range("A1", Range("A1").End(xlDown)).Count

    MsgBox ("Num rows in A = " & num_rows)

    num_rows_B = ws2.Range("A1", Range("A1").End(xlDown)).Count

    MsgBox ("Num rows in B = " & num_rows_B)
End Sub

当我运行代码时,如果A处于活动状态,则A的MsgBox起作用,而B的MsgBox出现此错误:

  

运行时错误'1004'应用程序定义或对象定义的错误。

  • 如果B处于活动状态,则会出现错误。

  • 如果我注释掉与A有关的所有三行,则B的MsgBox可以正常工作。

有什么办法可以访问两个工作簿吗?

我不了解限定工作表范围的含义。关于我可以去哪里阅读的任何建议?

谢谢。

1 个答案:

答案 0 :(得分:1)

在更新后的代码中,您仍然有2个不合格的Range-我在下面为您完全限定了他们的资格:

Sub Copy_and_Paste()

    Dim ws1 As Worksheet: Set ws1 = Workbooks("Submittals").Worksheets("Sheet1")
    Dim ws2 As Worksheet: Set ws2 = Workbooks("Previous").Worksheets("Sheet1")
    Dim num_rows_A As Integer
    Dim num_rows_B As Integer

    num_rows = ws1.Range("A1", ws1.Range("A1").End(xlDown)).Count

    MsgBox ("Num rows in A = " & num_rows)

    num_rows_B = ws2.Range("A1", ws2.Range("A1").End(xlDown)).Count

    MsgBox ("Num rows in B = " & num_rows_B)

End Sub