如何在每个工作表中设置相同的assign commandbutton

时间:2016-07-12 22:42:02

标签: excel vba excel-vba

每次插入具有相同名称的新闻表(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的编程访问不受信任"。怎么解决呢?

2 个答案:

答案 0 :(得分: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

答案 1 :(得分: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