按下按钮时会调用以下步骤。它应该添加一个新的工作表并重命名(代号)工作表对象/模块。这需要重命名,因为稍后的另一个过程会将代码添加到工作表模块。
Private Sub Add_OrderForms()
Worksheets.Add After:=Sheets(1)
ActiveSheet.Name = "Order Forms"
ThisWorkbook.VBProject.VBComponents(Worksheets("Order Forms").CodeName).Name = "OrderForms"
End Sub
但是,如果VB编辑器没有打开,我得到一个运行时错误9:下标超出范围。当编辑器打开时,我没有收到此错误。但客户不会打开编辑器。我应该首先声明任何变量吗?
答案 0 :(得分:1)
我不认为您可以在项目被锁定查看时更改项目。当VBE打开时,您已手动解锁它以及它的工作原理。但当它关闭时,它又被锁定了。
您可以删除保护,它将按照书面形式运行。你可能不想这样做,所以这里有另一种选择。使用所需的代号创建工作表并保存。然后,而不是创建新工作表,将该工作表复制到工作簿中。我使用订单表单Book3.xlsx
调用了我的工作簿Public Sub Add_OrderForms()
Dim wb As Workbook
Set wb = Workbooks.Open(ThisWorkbook.Path & Application.PathSeparator & "Book3.xlsx")
wb.Worksheets(1).Copy ThisWorkbook.Worksheets(1)
wb.Close False
End Sub
答案 1 :(得分:0)
试试这个:
Private Sub Add_OrderForms()
Debug.Print Activeworkbook.VBProject.Name
Worksheets.Add After:=Sheets(1)
ActiveSheet.Name = "Order Forms"
ThisWorkbook.VBProject.VBComponents(Worksheets("Order Forms").CodeName).Name = "OrderForms"
End Sub
答案 2 :(得分:0)
Private Sub Add_OrderForms()
Worksheets.Add After:=Sheets(1)
ActiveSheet.Name = "Order Forms"
DoEvents
DoEvents
ThisWorkbook.VBProject.VBComponents(Worksheets("Order Forms").CodeName).Name = "OrderForms"
End Sub
如果仍然不起作用,我建议application.ontime:
Private Sub Add_OrderForms()
Worksheets.Add After:=Sheets(1)
ActiveSheet.Name = "Order Forms"
Application.Ontime Now(), "UpdateOrderCodename"
End Sub
在正常模块中:
Public Sub UpdateOrderCodename()
ThisWorkbook.VBProject.VBComponents(Worksheets("Order Forms").CodeName).Name = "OrderForms"
End Sub
答案 3 :(得分:0)
对于它的价值,一个便宜的捷径是通过代码打开VBE然后再关闭它。虽然用户会看到VBE的快速闪烁,但它仍然可以实现您的目标。
Application.VBE.MainWindow.Visible = True
ThisWorkbook.VBProject.VBComponents(Worksheets("Order Forms").CodeName).Name = "OrderForms"
Application.VBE.MainWindow.Visible = False