【问题标题】:Display the 'File -> Print' menu via VBA通过 VBA 显示“文件 -> 打印”菜单
【发布时间】:2024-04-13 05:10:07
【问题描述】:

使用 VBA for Excel (2010) 我可以调用打印对话框和打印预览,但我不知道如何调用 文件 -> 打印 菜单。

Application.Dialogs(xlDialogPrint).Show ' Client - "not in keeping with the Excel 2010 experience"
ActiveSheet.PrintPreview (False)        ' Very slow to display

是否可以使用 VBA 显示此菜单选项?

【问题讨论】:

  • 你指的是你得到的屏幕:application.CommandBars.ExecuteMso "PrintPreviewAndPrint"

标签: excel printing vba


【解决方案1】:

这是你正在尝试的吗?

Sendkeys 不可靠,因此在使用它们时必须非常小心。

确保您从 Developer Tab | 调用它宏,而不是直接来自 VBA 编辑器。否则,您将不得不使用 API 将 Excel 窗口置于最前面,然后使用 sendkeys。

Sub Sample()
    SendKeys "%fp"
End Sub

这是一个从 VBE 调用它的示例

Private Declare Function SetForegroundWindow _
Lib "user32.dll" (ByVal hWnd As Long) As Long

Sub Sample()
    Dim CBC As CommandBarControl

    '~~> Bring the Excel window to the front.
    '~~> I am assuming that there is only one excel instance
    '~~> If there are more then you will have to use Findwindow,
    '~~> FindwindowEx API
    SetForegroundWindow ActiveWorkbook.Application.hWnd

    '~~> Closing the VBE
    On Error Resume Next
    Set CBC = Application.VBE.CommandBars.FindControl(ID:=752)
    On Error GoTo 0

    If Not CBC Is Nothing Then
        CBC.Execute
        DoEvents

        '~~> File --> Print
        SendKeys "%fp"
    End If
End Sub

【讨论】:

  • 谢谢,这正是我所需要的。