2013-10-17 12 views
0

我有下面的代碼,以動態創建按鈕:Excel的VBA的OnAction事件不工作,但不會出錯或者

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代碼中的子。我已經嘗試了一些在這裏和網上其他地方的例子,似乎無法讓他們工作。

任何人都知道我錯過了什麼?

+0

哪裏'CmdButton2_Click'子?如果不在常規模塊中,那麼你需要在其前面加上目標模塊名稱 - 例如'Sheet1.CmdButton2_Click' –

+1

'CmdButton2_Click'是什麼?確保它不是空白的。你的代碼對我來說很好。 –

+0

@TimWilliams:如果行動無法找到'CmdButton2_Click',它會給出錯誤。就像歐普提到的,他沒有收到任何錯誤... –

回答

0

作品對我來說

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 
+0

我需要做的是添加我的工作表名稱,就像你必須在OnAction事件中一樣。我嘗試過「Sheet!CmdClick」,但那不起作用,但是「Sheet.CmdClick」做了。 – Baub

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