0

我有以下动态创建按钮的代码:

Private Sub Worksheet_Change(ByVal Target As Range)
Dim i, sInfo As String


    For i = 2 To GetLastRow("Deliverables", "A")

    sInfo = "CmdButton" & i

    Me.Buttons(sInfo).Delete


    ActiveSheet.Buttons.Add(Cells(i, "AA").Left + Cells(i, "AA").Width * 0.05, Cells(i, "AA").Top + Cells(i, "AA").Height * 0.05, Cells(i, "AA").Width * 0.9, Cells(i, "AA").Height * 0.9).Select
    With Selection
        .Caption = "Update Task: " & Cells(i, "B").Value
        .Name = sInfo
        .Text = "Update Task: " & Cells(i, "B").Value
        Selection.OnAction = "CmdButton2_Click"

    End With
    Next
End Sub

这运行没有错误,但我似乎无法正常工作的是 Selection.OnAction 事件。当我单击按钮时,没有任何反应。我试图让 OnAction 事件调用 VBA 代码中的另一个 Sub。我从这里和网络上的其他地方尝试了一些例子,似乎无法让它们工作。

有人知道我错过了什么吗?

4

2 回答 2

1

为我工作

Private Sub Worksheet_Change(ByVal Target As Range)
Dim i, sInfo As String, c As Range
Dim rngUpdate As Range, rw As Range, r As Long
Dim tsk As String

    Set rngUpdate = Application.Intersect(Target, Me.Range("C2:G20"))

    If rngUpdate Is Nothing Then Exit Sub

    Set rngUpdate = rngUpdate.EntireRow

    For Each rw In rngUpdate.Rows

        r = rw(1).Row
        sInfo = "CmdButton" & r

        On Error Resume Next
        Me.Buttons(sInfo).Delete
        On Error GoTo 0

        Set c = ActiveSheet.Cells(r, "B")
        With ActiveSheet.Buttons.Add(c.Left + c.Width * 0.05, _
                                c.Top + c.Height * 0.05, _
                                c.Width * 0.9, c.Height * 0.9)

            .Caption = "Update Task: " & Cells(r, "C").Value
            .Name = sInfo
            tsk = Cells(r, "C").Value
            .Text = "Update Task: " & tsk
            .OnAction = "'Sheet1.CmdButton2_Click """ & tsk & """'"

        End With
    Next rw

End Sub

Sub CmdButton2_Click(r)
    Debug.Print "clicked update for : " & r
End Sub
于 2013-10-17T20:59:25.043 回答
0

我能够创建一个按钮并使用以下代码调用宏例程:

Sub CreateButton()
Dim I, sInfo As String
Dim sBut
    I = 2        
    sInfo = "CmdButton" & I

    ActiveSheet.Buttons(sInfo).Delete

    Set sBut = ActiveSheet.Shapes.AddFormControl(xlButtonControl, _
        Cells(I, "AA").Left + Cells(I, "AA").Width * 0.05, Cells(I, "AA").Top + Cells(I, "AA").Height * 0.05, Cells(I, "AA").Width * 0.9, Cells(I, "AA").Height * 0.9)
    With sBut
        .Name = sInfo
        .OnAction = "MyMacro"
        .TextFrame.Characters.Text = "Update Task: " & Cells(I, "B").Value
    End With
End Sub

Sub MyMacro()
MsgBox "You Clicked Me"
End Sub
于 2013-10-17T20:54:41.520 回答