首页 > 解决方案 > Excel VBA - 使用分配的代码动态创建按钮

问题描述

我正在尝试动态创建一些按钮,并为它们分配代码。

以下代码有效

Dim MyR As Range, MyB As OLEObject
Dim MyR_T As Long, MyR_L As Long


    Set MyR = Cells(i + 1, 11) 'just an example - you get that from your own script
    MyR_T = MyR.Top         'capture positions
    MyR_L = MyR.Left        '...
    'create button
    Set MyB = ActiveSheet.OLEObjects.Add(ClassType:="Forms.CommandButton.1", Link:=False, DisplayAsIcon:=False)


    'set main button properties
    With MyB

        .Name = "MyPrecodedButton"     'important - code must exist ... see below
        .Object.Caption = "MyCaption"
        .Top = MyR_T
        .Left = MyR_L
        .Width = 50
        .Height = 18
        .Placement = xlMoveAndSize
        .PrintObject = True            'or false as per your taste


    End With

它在我的循环中创建按钮。但是,我想为点击分配一些东西,所以我使用以下代码

Dim MyR As Range, MyB As OLEObject
Dim MyR_T As Long, MyR_L As Long


    Set MyR = Cells(i + 1, 11) 'just an example - you get that from your own script
    MyR_T = MyR.Top         'capture positions
    MyR_L = MyR.Left        '...
    'create button
    Set MyB = ActiveSheet.OLEObjects.Add(ClassType:="Forms.CommandButton.1", Link:=False, DisplayAsIcon:=False)


    'set main button properties
    With MyB
        .OnAction = "interpHere"
        .Name = "MyPrecodedButton"     'important - code must exist ... see below
        .Object.Caption = "MyCaption"
        .Top = MyR_T
        .Left = MyR_L
        .Width = 50
        .Height = 18
        .Placement = xlMoveAndSize
        .PrintObject = True            'or false as per your taste


    End With

    Sub interpHere()
        MsgBox "hi"
    End Sub

我基本上已经添加了.OnAction = "interpHere"但是当我运行它时,我得到一个错误,无法设置 onaction 属性。

我哪里错了?

标签: excelvbaexcel-formula

解决方案


试试这个代码

Sub CreateButtons()
  Dim btn As Button
  ActiveSheet.Buttons.Delete
  Dim t As Range
  For i = 2 To 6 Step 2
    Set t = ActiveSheet.Cells(i, 3)
    Set btn = ActiveSheet.Buttons.Add(t.Left, t.Top, t.Width, t.Height)
    With btn
      .OnAction = "interpHere"
      .Caption = "Btn " & i
      .Name = "Btn" & i
    End With
  Next i
End Sub

Sub interpHere()
    MsgBox "hi"
End Sub

推荐阅读