为什么我的VBA按钮在onAction调用上表现奇怪?

时间:2010-11-02 22:15:09

标签: debugging vba button

当调用我的VBA按钮的onAction方法时,我收到以下消息。 宏可能在此工作簿中不可用,或者可能禁用所有宏

在ThisWorkbook文件的test.xlsm中,我有一个非常简单的代码

Option Explicit
Private Sub Workbook_Open()
    UpdateMenuSR
End Sub
Private Sub UpdateMenuSR()
Dim cb As CommandBarButton
Dim Solver As CommandBar

For Each Solver In Application.CommandBars
    If Solver.name = "Test" Then Exit Sub
Next Solver

Set Solver = Application.CommandBars.Add("Test", msoBarFloating, False)
With Solver
    .Visible = True
    With .Controls
        Set cb = .Add(Type:=msoControlButton)
        With cb
            .FaceId = 31
            .Visible = True
            .OnAction = "!b"
        End With
        Set cb = .Add(Type:=msoControlButton)
        With cb
            .FaceId = 19
            .Visible = True
            .OnAction = "!c"
        End With
        Set cb = .Add(Type:=msoControlButton)
        With cb
            .FaceId = 30
            .Visible = True
            .OnAction = "!a"
        End With
        Set cb = .Add(Type:=msoControlButton)
        With cb
            .FaceId = 8
            .Visible = True
            .OnAction = "!d"
        End With
   End With
End With
End Sub
Private Sub Workbook_BeforeClose(Cancel As Boolean)
Dim ctrl As CommandBarControl
Application.CommandBars("Test").Delete
For Each ctrl In Application.CommandBars("Tools").Controls
    If ctrl.Tag = "Test" Or ctrl.Tag = "Test" Then
        ctrl.Delete
    End If
Next ctrl
End Sub

在Main模块中我只有

Public Sub a()
MsgBox "a"
End Sub


Public Sub d()
MsgBox "d"
End Sub


Public Sub b()
MsgBox "b"
End Sub


Public Sub c()
MsgBox "c"
End Sub

如果我执行以下程序:

  • 创建新文件test2.xlsx

  • 打开test.xlsm

  • 打开test2.xslx

  • 在按钮上依次点击:

结果:     “B”

"Cannot run the macro '[test.xslm]Sheet1A:A'. The macro may not be available in this   workbook or all macros may be disabled"

"a"

"Cannot run the macro 'd'. The macro may not be available in this workbook or all macros may be disabled"
  • 切换到test.xlsm

结果:

 "b"

"Cannot run the macro '[test.xslm]Sheet1A:A'. The macro may not be available in this wo rkbook or all macros may be disabled"

 "a"

 "d"

有人能帮帮我吗?

1 个答案:

答案 0 :(得分:0)

我遇到了问题。只需添加两个不可见的按钮:

    Set cb = .Add(Type:=msoControlButton)
    With cb
        .Visible = False
    End With

    Set cb = .Add(Type:=msoControlButton)
    With cb
        .Visible = False
    End With

因此可见按钮正常工作。