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

时间:2015-07-28 18:16:45

标签: excel vba excel-vba button

我正在尝试向Excel工作簿添加一个按钮,以便它显示在每个工作表中。我原来问题的一个很好的答案给了我一个宏来创建每张纸上的按钮:

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

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

 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很新,并且没有成功地使它工作。理想情况下,我会有一个创建按钮的按钮宏,每次按下时都会调用每张纸的打印宏。

最后一件事,我正在尝试更改按钮代码,以便它只向第5张纸张添加按钮。如果有人知道如何做到这一点会很棒吗?

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

2 个答案:

答案 0 :(得分:4)

试试这个:

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确定按钮大小。

答案 1 :(得分:1)

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

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

现在仅从 Sheet 5 开始添加按钮,您可以尝试:

  1. 制作所有工作表名称的列表(如果只有少数几个)

    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. 反过来做。列出要排除的内容并测试每个工作表是否在列表中。

    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
    
  3. 您的测试子将在上述样本中使用。

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