2016-07-12 27 views
0

我想每次插入具有相同名稱(TestButton)的報表時都要創建commandButon。希望如果CommandButton單擊將調用過程測試程序。這適用於所有工作表中的CommandButton。我的代碼如下:如何在每個工作表中設置相同的分配命令按鈕

Private Sub Workbook_NewSheet(ByVal Sh As Object) 
Dim Obj As Object 
Dim Code As String 
Dim LF As String 'Line feed or carriage return 

LF = Chr(13) 


Set Obj = ActiveSheet.OLEObjects.Add(ClassType:="Forms.CommandButton.1", _ 
      Link:=False, DisplayAsIcon:=False, Left:=880, Top:=20, Width:=100, Height:=50) 
Obj.Name = "TestButton" 
'buttonn text 
ActiveSheet.OLEObjects(1).Object.Caption = "Send" 

'macro text 
    Code = "Sub TestButton_Click()" & LF 
    Code = Code & "Call Tester" & LF 
    Code = Code & "End Sub" 
'add macro at the end of the sheet module 
    With ActiveWorkbook.VBProject.VBComponents(ActiveSheet.Name).CodeModule 
       .insertlines .CountOfLines + 1, Code 
    End With 
End Sub 

Sub Tester() 
MsgBox "You have click on the test button" 
End Sub 

,但我得到一個錯誤消息「運行時錯誤1004到Visual Basic編程訪問不受信任」。如何解決它?

回答

1

您應該設置一個工作表你想要的和隱藏。使用該工作表作爲模板。無論何時添加工作表,請將其替換爲模板的副本。

Private Sub Workbook_NewSheet(ByVal Sh As Object) 
    Dim WorkSheetName As String 

    Dim i As Integer 
    With Application 
     .ScreenUpdating = False 
     .EnableEvents = False 
     .DisplayAlerts = fasle 

     i = Sh.Index 

     Worksheets("HiddenTempalte").Copy After:=Worksheets(i) 


     WorkSheetName = Sh.Name 

     Sh.Delete 

     Worksheets(i).Name = WorkSheetName 

     .DisplayAlerts = True 
     .EnableEvents = True 
     .ScreenUpdating = True 
    End With 

End Sub 
0

「信任訪問VBA項目」:

How to check from .net code whether "Trust access to the VBA project object model" is enabled or not for an Excel application?

考慮使用表單按鈕,而不是:

Private Sub Workbook_NewSheet(ByVal Sh As Object) 

    With Sh.Buttons.Add(Left:=880, Top:=20, Width:=100, Height:=50) 
     .Caption = "Send" 
     .OnAction = "Tester" 
    End With 

End Sub 

Public Sub Tester() 
    MsgBox "You have click on the test button" 
End Sub 
+0

謝謝蒂姆。但是當我按下發送按鈕時,沒有消息框出現。 – sandara

相關問題