如何将代码导入另一个页面上的Activex控制按钮?

时间:2016-02-01 04:08:50

标签: excel vba excel-vba

我使用了一个按钮(通过点击)来创建一个新工作表并在其上插入一个按钮,但我想将代码导入到新按钮(这里是MyPrecodedButton)。

Private Sub CommandButton1_Click()
Dim z As Integer
Dim wb As Workbook
Dim ws2 As Worksheet, wsnew As Worksheet

Set wb = ThisWorkbook
Set ws2 = wb.Sheets("Sheet2")

z = ws2.Cells(2, 1).Value

Set wsnew = Sheets.Add ' Declare your New Sheet in order to be able to work with after
wsnew.Name = "PIAF_Summary" & z

z = z + 1

With wsnew.Range("A1:G1")
        .Merge
        .Interior.ColorIndex = 23
        .Value = "Project Name (To be reviewed by WMO)"
        .Font.Color = vbWhite
        .Font.Bold = True
        .Font.Size = 13
 End With
ws2.Cells(2, 1).Value = z

Dim Rngc As Range: Set Rngc = wsnew.Range("F35")
With ActiveSheet.OLEObjects.Add(ClassType:="Forms.CommandButton.1", Link:=False, DisplayAsIcon:=False, Left:=Rngc.Left, Top:=Rngc.Top, Width:=205, Height:=20)
    .Name = "MyPrecodedButton" ' change the name
End With
End sub

以下是MyPrecodedButton的代码

Public Sub MyPrecodedButton_Click()
    MsgBox "Co-Cooo!"
End Sub

1 个答案:

答案 0 :(得分:1)

让我们简要介绍一下使用VBA添加按钮可以做些什么。

如果ActiveSheet不是“Sheet1”,则代码下方会向单元格B2添加一个按钮。

Option Explicit

Sub SayHello()
    MsgBox "Hello from """ & ActiveSheet.Name & """"
End Sub

Sub AddButton()
    Dim oRng As Range
    Dim oBtns As Buttons ' Add "Microsoft Forms 2.0 Object Library" to References if you want intellisense
    If ActiveSheet.Name <> "Sheet1" Then ' Only works if it's not "Sheet1"
        Set oRng = Range("B2")
        Set oBtns = ActiveSheet.Buttons
        With oBtns.Add(oRng.Left * 1.05, oRng.Top * 1.05, oRng.Width * 0.9, oRng.Height * 2 * 0.9)
            .Caption = "Say Hello!"
            .OnAction = "SayHello"
        End With
        Set oBtns = Nothing
        Set oRng = Nothing
    End If
End Sub

截图前后:
Before After

现在点击按钮:
Action

因此,如果您的代码足够通用(适用于所有可能的情况),则无需通过代码添加代码。即准备好您的代码,然后只需指定按钮的OnAction属性即可调用正确的Sub