在我的工作簿(Book1)中,我有一个命令按钮,用于打开一个新的工作簿,将两个用户窗体导入到新的工作簿中,并创建两个命令按钮。
但是,如果我想单击这些命令按钮之一,则错误消息“编译错误:对象库无效或包含对找不到的对象定义的引用。”
如果我手动创建一个新工作簿,请通过拖放导入UF,并创建Buttons,一切正常。
这是我的宏:
' Book1 CommandButton
Private Sub PM_Controlling_Click()
Dim relativePath As String
Dim btn1 As Object
Dim Code As String
' Create new Book:
Workbooks.Add
relativeString = ThisWorkbook.Path & "\Book2"
ActiveWorkbook.SaveAs Filename:=relativeString & ".xlsm", FileFormat:=xlOpenXMLWorkbookMacroEnabled
' Import UserForm:
Workbooks("Book2.xlsm").VBProject.VBComponents.Import Filename:="C:\Users\UserForm\Add\UserForm1.frm"
Workbooks("Book2.xlsm").VBProject.VBComponents.Import Filename:="C:\Users\UserForm\Add\UserForm2.frm"
' Create Button for UserForm1:
Set btn = ActiveSheet.OLEObjects.Add(ClassType:="Forms.CommandButton.1", Link:=False, DisplayAsIcon:=False, Left:=10, Top:=10, Width:=110, Height:=25)
ActiveSheet.OLEObjects(1).Object.Caption = "Project Report"
btn.Name = "Project_Report"
' Code for UserForm1:
Code = "Private Sub Project_Report_Click()" & vbCrLf
Code = Code & " [UserForm1].Show" & vbCrLf
Code = Code & "End Sub"
With ActiveWorkbook.VBProject.VBComponents(Worksheets(ActiveSheet.Name).CodeName).CodeModule
.insertlines .CountOfLines + 1, Code
End With
' Create Button for UserForm2:
Set btn = ActiveSheet.OLEObjects.Add(ClassType:="Forms.CommandButton.1", Link:=False, DisplayAsIcon:=False, Left:=10, Top:=40, Width:=110, Height:=25)
ActiveSheet.OLEObjects(2).Object.Caption = "Watch Project Report"
btn.Name = "Watch_Report"
' Code for UserForm2:
Code = "Private Sub Watch_Report_Click()" & vbCrLf
Code = Code & " [UserForm2].Show" & vbCrLf
Code = Code & "End Sub"
With ActiveWorkbook.VBProject.VBComponents(Worksheets(ActiveSheet.Name).CodeName).CodeModule
.insertlines .CountOfLines + 1, Code
End With
End Sub
' Code in Book2
Private Sub Project_Report_Click()
[UserForm1].Show
End Sub
Private Sub Watch_Report_Click()
[UserForm2].Show
End Sub
' UserForm1 Code
Private Sub CommandButton1_Click()
UserForm2.Label1 = TextBox1.Value
UserForm2.Label2 = TextBox2.Value
UserForm2.Label3 = TextBox3.Value
UserForm2.Label4 = TextBox4.Value
[UserForm1].Hide
End Sub
Private Sub CommandButton2_Click()
[UserForm1].Hide
End Sub
'UserForm2 Code
Private Sub CommandButton1_Click()
[UserForm2].Hide
End Sub
Book2 [UserForm1]中的零件。显示以蓝色突出显示,并导致错误。
希望有人可以帮助我解决这个问题。