宏运行,但实际上不能在“打印预览”模式下工作

时间:2018-03-26 15:07:54

标签: excel excel-vba vba

只要选择了A列中的单个单元格,下面的代码就会在Excel的单元格菜单中添加一个项目(通过右键单击一个单元格来访问)。

在普通视图中查看文档时,它按预期工作,但是当选择“打印预览”时,代码会运行,但该项目永远不会添加到单元格菜单中。

要测试这一点,只需将下面的代码粘贴到Visual Basic编辑器中的Sheet1代码窗口中,然后右键单击A列中的单元格。您将在上下文顶部看到一个带有笑脸图标的新菜单项菜单。

现在切换到“打印预览”,然后右键单击A列中的单元格。菜单项不会出现。如果在AddToCellMenu_Comments子中设置断点,那么您可以看到代码正在运行,但它没有效果!

Option Base 0
Option Explicit

Private Sub Worksheet_SelectionChange(ByVal Target As Range)
    If Target.Columns.Count = 1 And Target.Rows.Count = 1 Then
        If Target.Column = 1 Then
            AddToCellMenu_Comments
        Else
            DeleteFromCellMenu
        End If
    Else
        DeleteFromCellMenu
    End If
End Sub


Public Sub AddToCellMenu_Comments()
    Dim ContextMenu As CommandBar
    Dim MySubMenu As CommandBarControl

    ' Delete the controls first to avoid duplicates.
    Call DeleteFromCellMenu

    ' Set ContextMenu to the Cell context menu.
    Set ContextMenu = Application.CommandBars("Cell")

    ' Add one custom button to the Cell context menu.
    With ContextMenu.Controls.Add(Type:=msoControlButton, before:=1)
        .FaceId = 59
        .Caption = "Configure Comments"
        .Tag = "My_Cell_Control_Tag"
    End With

End Sub

Public Sub DeleteFromCellMenu()
    Dim ContextMenu As CommandBar
    Dim ctrl As CommandBarControl

    ' Set ContextMenu to the Cell context menu.
    Set ContextMenu = Application.CommandBars("Cell")

    ' Delete the custom controls with the Tag : My_Cell_Control_Tag.
    For Each ctrl In ContextMenu.Controls
        If ctrl.Tag = "My_Cell_Control_Tag" Then
            ctrl.Delete
        End If
    Next ctrl

    ' Delete the custom built-in Save button.
    On Error Resume Next
    ContextMenu.FindControl(ID:=3).Delete
    On Error GoTo 0
End Sub

只是添加 它也适用于“页面布局”视图。这只是“打印预览”视图无效。

0 个答案:

没有答案