我根据单元格值制作了几个通过右键菜单按钮运行的宏。通常,如果我右键单击值为“XYZ”的单元格,菜单按钮显示为“运行XYZ的宏”,然后执行一系列操作:显示几个用户表单,运行SQL查询,显示和格式化结果数据
在原始的.xlsm文件中,在'Thisworkbook'上我有以下代码:
Public WithEvents mxlApp As Application
Public WithEvents mxlSh As Worksheet
Private Sub mxlApp_SheetBeforeRightClick(ByVal Sh As Object, ByVal Target As Range, Cancel As
Boolean)
... (do stuff here) ...
End Sub
...
Private Sub Workbook_Open()
Call AutoExec
End Sub
...
在单独的模块中,我有以下用于设置事件处理程序的函数
Public Sub AutoExec()
Set mxlApp = Application
Set ColectionOfMxlEventHandlers = New Collection
ColectionOfMxlEventHandlers.Add mxlApp
Debug.Print ThisWorkbook.Name & " Initialized"
End Sub
问题:在原始.xlsm文件中,代码工作正常:每次我右键单击符合特定条件的单元格时,我都会得到“为XYZ运行宏”,一切都很好。
将文件另存为.xlam并将其加载为插件后,代码将无效。
我一直在互联网上看到这里,并且无法弄清楚如何解决这个问题。
编辑:
在修改了creamyegg所建议的代码之后,这就是我所拥有的:
在课程模块clsAppEvents
中:
Private WithEvents mxlApp As Excel.Application
Private Sub Class_Initialize()
Set mxlApp = Excel.Application
End Sub
Private Sub mxlApp_SheetBeforeRightClick(ByVal Sh As Object, ByVal Target As Range, Cancel As Boolean)
Dim cBut As CommandBarButton
On Error Resume Next
Call CleanMenu
If Len(Target.Value) = 8 Then
MyId = Target.Value
With Application
Set cBut = .CommandBars("Cell").Controls.Add(Temporary:=True)
End With
With cBut
.Caption = "Run SQL Query for " & MyId
.Style = msoButtonCaption
.FaceId = 2554
.OnAction = "CallGenericQuery"
End With
End If
With Application
Set cBut = .CommandBars("Cell").Controls.Add(Temporary:=True)
End With
With cBut
.Caption = "Columns_Select"
.Style = msoButtonCaption
.FaceId = 255
.OnAction = "CallShowHide"
End With
On Error GoTo 0
End Sub
在Thisworkbook
课程中
Public m_objMe As clsAppEvents
Private Sub Workbook_Open()
Set m_objMe = New clsAppEvents
Debug.Print ThisWorkbook.Name & " Initialized"
End Sub
Private Sub Workbook_BeforeClose(Cancel As Boolean)
On Error Resume Next
Call CleanMenu
On Error GoTo 0
Set m_objMe = Nothing
End Sub
Private Sub Workbook_Deactivate()
Call CleanMenu
End Sub
MyId
被定义为主模块中包含CallShowHide
和callGenericQuery
潜艇
答案 0 :(得分:1)
问题听起来似乎WithEvents
仍在ThisWorkbook
班级?您需要做的是创建一个新类,然后在加载项的Workbook_Open()
事件中实例化此实例。例如:
新班级(clsAppEvents
):
Private WithEvents mxlApp As Excel.Application
Private Sub Class_Initialize()
Set mxlApp = Excel.Application
End Sub
Private Sub mxlApp_SheetBeforeRightClick(ByVal Sh As Object, ByVal Target As Range, Cancel As Boolean)
...
End Sub
加载项ThisWorkbook
类:
Private m_objMe As clsAppEvents
Private Sub Workbook_Open()
Set m_objMe = New clsAppEvents
End Sub
Private Sub WorkbookBeforeClose(Cancel As Boolean)
Set m_objMe = Nothing
End Sub