VBA代码:不同的工作表显示不同的弹出菜单

2022-11-16 10:15:04 浏览数 (2)

标签:VBA,快捷菜单

如果想要对每个工作表显示不同的菜单,或者仅在某些工作表中显示菜单,可以使用相应的代码来实现。

在VBE中,单击菜单“插入——模块”,在标准模块中,输入下面的代码:

Sub Custom_PopUpMenu_2()

' 添加带有3个按钮的弹出菜单.

With Application.CommandBars.Add(Name:=Mname, _

Position:=msoBarPopup, _

MenuBar:=False, _

Temporary:=True)

With .Controls.Add(Type:=msoControlButton)

.Caption = "按钮 1"

.FaceId = 71

.OnAction = "'" & ThisWorkbook.Name & "'!" & "TestMacro"

End With

With .Controls.Add(Type:=msoControlButton)

.Caption = "按钮 2"

.FaceId = 72

.OnAction = "'" & ThisWorkbook.Name & "'!" & "TestMacro"

End With

With .Controls.Add(Type:=msoControlButton)

.Caption = "按钮 3"

.FaceId = 73

.OnAction = "'" & ThisWorkbook.Name & "'!" & "TestMacro"

End With

End With

End Sub

Sub CreateDisplayPopUpMenu()

' 如果存在则删除该弹出菜单.

Call DeletePopUpMenu

' 基于活动工作表创建合适的菜单.

Select Case ActiveSheet.Name

Case "Sheet1": Call Custom_PopUpMenu_1

Case "Sheet2": Call Custom_PopUpMenu_2

Case Else: MsgBox "Sorry no Popup Menu"

End Select

' 显示弹出菜单.

On Error Resume Next

Application.CommandBars(Mname).ShowPopup

On Error GoTo 0

End Sub

接着,输入下面的代码:

Sub CreateDisplayPopUpMenu()

' 如果存在则删除该弹出菜单.

Call DeletePopUpMenu

' 基于活动工作表创建合适的菜单.

Select Case ActiveSheet.Name

Case "Sheet1": Call Custom_PopUpMenu_1

Case "Sheet2": Call Custom_PopUpMenu_2

Case Else: MsgBox "Sorry no Popup Menu"

End Select

' 显示弹出菜单.

On Error Resume Next

Application.CommandBars(Mname).ShowPopup

On Error GoTo 0

End Sub

此时,在工作表Sheet1和工作表Sheet2中,将显示不同的菜单,而在其他工作表中,会显示“Sorry no Popup Menu”消息。

注:本文整理自microsoft.com,供有兴趣的朋友参考。

欢迎在下面留言,完善本文内容,让更多的人学到更完美的知识。

0 人点赞