如何在 VBA 中添加命令按钮?

How to add a command button in VBA?

我正在尝试向 Excel 工作簿添加一个按钮,以便它显示在每个 sheet 中。对我最初问题的一个很好的回答给了我一个宏来在每个 sheet:

上创建按钮
Sub AddButtons()
    Dim ws As Excel.Worksheet
    Dim btn As Button

    For Each ws In ThisWorkbook.Worksheets
        Set btn = ws.Buttons.Add(X, Y, W, H)
        [set btn properties]
    Next ws
End Sub

我现在无法设置按钮属性,以便按钮在按下时打印 sheet。这是我的打印宏:

 Dim WS_Count As Integer
 Dim i As Integer

 ' Set WS_Count equal to the number of worksheets in the active workbook.
 WS_Count = ActiveWorkbook.Worksheets.Count
 'allows user to set printer they want to use
 Application.Dialogs(xlDialogPrinterSetup).Show
 ' Begin the loop.
 For i = 5 To WS_Count
   Worksheets(i).Activate
   With ActiveWorkbook.Worksheets(i).PageSetup
     .PrintArea = "A1:O48"
     .Orientation = xlLandscape
     .Zoom = False
     .FitToPagesTall = 1
     .FitToPagesWide = 1
   End With
   ActiveWorkbook.Worksheets(i).PrintOut

关于如何将此宏合并到按钮属性(传递变量和创建新的打印子)有一些很好的建议,但是我对 VBA 很陌生并且没有成功这个工作。理想情况下,我会有一个创建按钮的按钮宏,每次按下它都会为每个 sheet 调用打印宏。

最后一件事,我正在尝试更改按钮代码,以便它只向 sheet 5 添加按钮。如果有人也知道该怎么做,那就太好了?

任何建议都很有帮助,非常感谢!

试试这个:

Sub AddButtons()
    Dim ws As Excel.Worksheet
    Dim btn As Button

    For Each ws In ThisWorkbook.Worksheets
        Set btn = ws.Buttons.Add(X, Y, W, H)
        btn.OnAction = "MySub"    ' MySub is executed when btn is clicked
        ' Substitute the name of your printing subroutine
        btn.Caption = "Print"
        'set additional btn properties as needed
    Next ws
End Sub

XY 确定位置,WH 确定按钮大小。

这将添加一个按钮(表单控件)并为其分配一个现有的宏。

Sub test()
    Dim cb As Shape
    Set cb = Sheet1.Shapes.AddFormControl(xlButtonControl, 10, 10, 100, 25)
    cb.OnAction = "PrintMacro"
End Sub

Private Sub PrintMacro()
    MsgBox "Test" ' for testing pursposes
    ' you actually put your print code here
End Sub

现在只添加Sheet5以后的按钮,你可以试试:

  1. 生成所有 sheet 名字的列表(如果只有几个)

    Dim shname
    For Each shname In Array("Sheet 5", "Sheet 6", "Sheet 7")
        test Sheets(shname) ' note that you'll have to use below test sub
    Next
    
  2. 反过来做。列出要排除的内容并测试每个 sheet 是否在列表中。

    Dim sh As Worksheet
    Dim xcludesheet: xcludesheet = Array("Sheet1", "Sheet2", "Sheet3", "Sheet4")
    For Each sh In Worksheets
        If IsError(Application.Match(sh.Name, xcludesheet, 0)) Then
            test Sheets(sh.Name)
        End If
    Next
    

您将在上述示例中使用的测试子。

Sub test(ws As Worksheet)
    Dim cb As Shape
    Set cb = ws.Shapes.AddFormControl(xlButtonControl, 10, 10, 100, 25)
    cb.OnAction = "PrintMacro"
End Sub