宏可以单独工作,但在一起运行时会出错

时间:2017-07-11 14:09:15

标签: excel vba excel-vba

我在类模块下有一个VBA代码:

Option Explicit
Public WithEvents MyQuery As QueryTable

Private Sub MyQuery_AfterRefresh(ByVal Success As Boolean)

MsgBox ("data is refreshed")
MsgBox ("about to clear key ranks")
Call Module2.ClearKeyRanks

MsgBox ("about to vlookup")
Call Module2.VL

MsgBox ("about to replace 0's")

Call Module2.replace_zeros

MsgBox ("about to sort keys")
Call Module2.SortKey
MsgBox ("about to refresh pvt")
Call Module2.refreshDisplayPivot
MsgBox ("querie initialized")
Call InitializeQueries
End Sub

Private Sub MyQuery_BeforeRefresh(Cancel As Boolean)

Call Module1.InitializeQueries

MsgBox ("about to sort keys")
Call Module2.SortKey

MsgBox ("about to clear mem")
Call Module2.ClearMem

MsgBox ("about to memranks")
Call Module2.memRanks
MsgBox ("about to refresh")
End Sub

当我在工作簿中单独运行这些宏中的每一个时,它工作正常。然而,当我尝试通过点击"全部刷新"在工作簿中的选项,它会执行这些步骤并向我抛出运行时错误50290:应用程序定义的错误或对象定义的错误"对于Module2.ClearKeyRanks步骤。该代码是:

 Sub ClearKeyRanks()

Dim key As Object ' Excel Worksheet
Set key = ThisWorkbook.Worksheets("Key")

key.Range("B2:B10000").ClearContents

我也尝试过Dim key As Worksheets,它仍然会引发同样的错误。根据我的理解,错误在key.Range(" B2:B10000").ClearContents行,但我不知道如何解决这个问题。任何帮助表示赞赏!

1 个答案:

答案 0 :(得分:0)

我刚注意到你没有为Module2声明一个变量。我假设Module2是该类的名称?....

Private Sub MyQuery_AfterRefresh(ByVal Success As Boolean)

MsgBox ("data is refreshed")
MsgBox ("about to clear key ranks")

'declare a variable for the class
Dim myModule2 As Module2
'Initialize the variable
Set myModule2 = New Module2
'call the objects methods
Call myModule2.ClearKeyRanks

MsgBox ("about to vlookup")
Call myModule2.VL

MsgBox ("about to replace 0's")

Call myModule2.replace_zeros

MsgBox ("about to sort keys")
Call myModule2.SortKey
MsgBox ("about to refresh pvt")
Call myModule2.refreshDisplayPivot
MsgBox ("querie initialized")
Call InitializeQueries
End Sub