我看到Username Rory发布的一些代码,并想编辑它,以便我可以从功能区中的加载项运行我的宏。将它们全部粘贴在ThisWorkBook模块后,它会在那里添加功能区按钮,但每次点击它我都会得到:
宏可能在此工作簿中不可用,或者所有宏都可能被禁用"
我很确定我从Excel选项中启用了所有宏选项。以下是代码,全部在" ThisWorkBook":
下Private Const Button As String = "SomeName"
Sub Auto_Open()
Dim CmdBar As CommandBar
Dim CmdBarMenu As CommandBarControl
Dim CmdBarMenuItem As CommandBarControl
Set CmdBar = Application.CommandBars("Worksheet Menu Bar")
Set CmdBarMenu = CmdBar.Controls("Tools") ' Index 6
On Error Resume Next
Application.DisplayAlerts = False
CmdBarMenu.Controls(Button).Delete
Application.DisplayAlerts = True
On Error GoTo 0
Set CmdBarMenuItem = CmdBarMenu.Controls.Add(Type:=msoControlButton)
With CmdBarMenuItem
.Caption = Button
.OnAction = "Hello"
End With
End Sub
Sub Auto_Close()
Dim CmdBar As CommandBar
Dim CmdBarMenu As CommandBarControl
Set CmdBar = Application.CommandBars("Worksheet Menu Bar")
Set CmdBarMenu = CmdBar.Controls("Tools") ' Index 6
On Error Resume Next
Application.DisplayAlerts = False
CmdBarMenu.Controls(Button).Delete
Application.DisplayAlerts = True
On Error GoTo 0
End Sub
Sub Hello()
MsgBox ("Hello")
End Sub
答案 0 :(得分:0)
所以这里的代码给你的错误是'.onAction',如下所示:
With CmdBarMenuItem
.Caption = Button
.OnAction = "Hello"
End With
这里的想法是你需要将“Hello”重新编程为一个宏。现在它正在寻找一个名为'Hello'的子程序,它无法找到它。如果您将所有代码都放在“ThisWorkbook”中,我建议在此处表示,以使其更强类型化。下面是一个示例,如果您希望按钮调用您在ThisWorkbook中创建的名为“MyClick_Event”的例程:
With CmdBarMenuItem
.Caption = Button
.OnAction = "ThisWorkbook.MyClick_Event"
End With
您还可以从其他VBA表创建调用,例如:
With CmdBarMenuItem
.Caption = Button
.OnAction = "Sheet1.MyClick_Event"
End With