如果工作簿中有多个vba宏,则应打开VBA窗口,然后在需要运行代码时选择宏。 在本文中,我想谈谈如何从右键菜单中运行宏,以便在显示左侧屏幕截图时提高工作效率。
使用VBA代码从右键菜单中运行多个宏
使用VBA代码从右键菜单中运行多个宏
要从右键单击菜单中运行工作簿中的宏代码,以下步骤可能对您有所帮助,请按以下步骤操作:
1。 钻孔了 Alt + F11键 键打开 Microsoft Visual Basic for Applications 窗口。
2。 然后,双击 的ThisWorkbook 在左边 项目 窗格,然后将以下VBA代码复制并粘贴到空白模块中。
Private Sub Workbook_Open()
Run "LoadMacro"
End Sub
Private Sub Workbook_Activate()
Run "LoadMacro"
End Sub
Private Sub Workbook_Deactivate()
Run "ClearMacro"
End Sub
Private Sub Workbook_BeforeClose(Cancel As Boolean)
Run "ClearMacro"
ThisWorkbook.Save
End Sub
3。 还在 Microsoft Visual Basic for Applications 窗口,请点击 插页 > 模块,并将以下代码粘贴到此模块中。
Private Sub LoadMacro()
Dim xArrMenu As Variant
Dim xStrLine, xSreBtnName As String
Dim xObjCBCF, xObjCntrAll As CommandBarControl
Dim xObjCBCs As CommandBars
Dim xObjCBBtn As CommandBarButton
Dim xIntLine, xFNum As Integer
Dim xObjComponent As Object
Run "ClearMacro"
Set xObjCBCF = Application.CommandBars("Cell").Controls.Add(msoControlPopup, before:=1)
xObjCBCF.Caption = " Run Macro "
xObjCBCF.BeginGroup = False
For Each xObjComponent In ActiveWorkbook.VBProject.VBComponents
If xObjComponent.Type = 1 Then
For xIntLine = 1 To xObjComponent.CodeModule.CountOfLines
xStrLine = xObjComponent.CodeModule.Lines(xIntLine, 1)
xStrLine = Trim(xStrLine)
If (InStr(xStrLine, "()") > 0) And (Left(xStrLine, 11) = "Private Sub" Or Left(xStrLine, 3) = "Sub") Then
xSreBtnName = ""
If "Private Sub" = Left(xStrLine, 11) Then
xSreBtnName = Trim(Mid(xStrLine, 12, InStr(xStrLine, "()") - 12))
ElseIf "Sub" = Left(xStrLine, 3) Then
xSreBtnName = Trim(Mid(xStrLine, 4, InStr(xStrLine, "()") - 4))
End If
If xSreBtnName <> "" And xSreBtnName <> "RightClickReset" And xSreBtnName <> "LoadMacro" And xSreBtnName <> "ActionMacro" Then
Set xObjCBBtn = xObjCBCF.Controls.Add
With xObjCBBtn
.FaceId = 186
.Style = msoButtonIconAndCaption
.Caption = xSreBtnName
.OnAction = "ActionMacro"
End With
End If
End If
Next xIntLine
End If
Next xObjComponent
End Sub
Private Sub ClearMacro()
On Error Resume Next
CommandBars("Cell").Controls(" Run Macro ").Delete
Err.Clear
CommandBars("Cell").Reset
End Sub
Private Sub ActionMacro()
On Error GoTo Err1
With Application
Run .CommandBars("Cell").Controls(1).Controls(.Caller(1)).Caption
End With
Exit Sub
Err1:
MsgBox "Invalid"
End Sub
4。 粘贴代码后,单击 工具 > 参考文献和一个 参考-的VBAProject 弹出对话框,然后检查 Microsoft Visual Basic for Applications可扩展性5.3 在选项 可用的参考 列表框,看截图:
5。 然后点击 OK 现在,要退出对话框,您应该将此工作簿保存为 Excel宏启用工作簿 格式,请参阅截图:
6。 最后,请重新启动工作簿以获取代码效果,现在,当您右键单击一个单元格时,a 运行宏 选项被插入到右键菜单中,工作簿中的所有宏都列在子菜单中,如下面的屏幕截图所示:
7。 然后,您只需单击它即可运行代码。 |