Excel 2007 VBA 添加一个按钮

Excel 2007 VBA to add a button

我正在尝试编写一些代码来自动将一个按钮放入我的工作表中,当单击该按钮时它会执行一些代码。我根据 "Excel 2013 Power Programming with VBA" (p896) 一书中看到的示例编写了代码。我正在使用 Excel 2007,但不确定它是否重要。无论如何,我将代码修改为以下:

*Sub AddButtonAndCode()  
Dim NewButton As OLEObject  
Dim NewSheet As Worksheet  
Set NewSheet = Worksheets("Sheet1")  
Set NewButton = NewSheet.OLEObjects.Add(ClassType:="Forms.CommandButton.1", Left:=5, Top:=5, Height:=25, Width:=100)  
Code = "Sub CommandButton1_Click()" & vbCrLf  
Code = Code & "  MsgBox ""???""" & vbCrLf  
Code = Code & "End Sub"
With ActiveWorkbook.VBProject.VBComponents(NewSheet.Name).CodeModule
    NextLine = .CountOfLines + 1
    .InsertLines NextLine, Code
End With
End Sub*

它适用于按钮部分,但在我添加下面定义按钮的部分后,出现错误 "Subscript out of range"

谁能帮我弄清楚那里出了什么问题?

非常感谢!

你的代码经过一些调整后对我有用。

Sub AddButtonAndCode()

    Dim NewButton As OLEObject
    Dim NewSheet As Worksheet, Code As String
    Dim nextline As Long

    Set NewSheet = Worksheets("Sheet1")

    Set NewButton = NewSheet.OLEObjects.Add(ClassType:="Forms.CommandButton.1", _
                       Left:=5, Top:=5, Height:=25, Width:=100)

    NewButton.Name = "CommandButton1"  '<<<<<<<<< ensure correct name

    Code = "Sub CommandButton1_Click()" & vbCrLf
    Code = Code & "  MsgBox ""???""" & vbCrLf
    Code = Code & "End Sub"

    'Use NewSheet.CodeName not NewSheet.Name
    With ActiveWorkbook.VBProject.VBComponents(NewSheet.CodeName).CodeModule
        nextline = .CountOfLines + 1
        .InsertLines nextline, Code
    End With

End Sub

在新的工作簿中,sheet 的 NameCodeName 将相同,因此您的原始行在这种情况下可以工作,但如果sheet或其代码模块已重命名。