excel vba中工作表sheet写入button的事件响应代码

2025-03-17 01:40:26
推荐回答(2个)
回答1:

程序不能运行的主要问题在于 InsertLines 方法中少了一个 t,仔细对照就知道了。

但另外的问题是你代码逻辑上有点问题,你想在所有工作表上写代码,如下修改就行:

For num1 = 1 To ThisWorkbook.Worksheets.Count
   With ThisWorkbook.VBProject.VBComponents("sheet" & num1).CodeModule
      .InsertLines 1, "Private Sub Btn002001_Click()"
      .InsertLines 2, "Call chancecheckbox"
      .InsertLines 3, "End Sub"
   End With
Next

回答2:

试试这个:
Dim feedname As String
For num1 = 1 To ThisWorkbook.Worksheets.Count + 1
feedname = ThisWorkbook.VBProject.VBComponents(num1).Name
Set newmodule = ThisWorkbook.VBProject.VBComponents(feedname)
strCode = "Private Sub Btn002001_Click()"
strCode = strCode & Chr(10) & "Call chancecheckbox"
strCode = strCode & Chr(10) & "End Sub"
newmodule.CodeModule.AddFromString strCode
Next
原因:ThisWorkbook.Worksheets.Count只能返回工作表的数量,而VB对象多了一个ThisWorkbook,而且是第一个。