从另一个用户窗体中的一个文件调用

写VBA代码调用一个Excel文件的用户窗体到名为john的文件夹中存在的所有其他Excel文件,而主Excel(由以下代码和用户窗体组成)存在于不同的位置:

  Private Sub Workbook_OnClick() Dim mypath As String Dim file As String Dim wb As Workbook Dim pat As String Application.ScreenUpdating = False ChDrive "C:" ChDir "C:\Users\Administrator\Desktop\John" 'john is a folder that consists of the excel files mypath = Range("B1").Value 'mypath has the same value as chDir file = Dir(mypath & "\" & "*.xlsx") Do While file <> "" Set wb = Application.Workbooks.Open(file) If Not IsEmpty(wb) Then Application.Visible = False userform1.Show End If wb.Close file = Dir() Loop End Sub 

该代码是拉主Excel文件,而不是在john文件夹中的Excel文件UserForm。

包含您要显示的用户窗体的工作簿还应该有一个显示窗体的过程。 您将需要调用过程来显示用户窗体。 它可以是一个函数或子,我更喜欢函数,因为那么你可以返回一个成功/失败的error handling。

在UserForm工作簿中,您将在Module1(或任何模块,但您需要稍后引用它)中添加一个像这样的过程:

 Public Function ShowTheForm(Optional Modal As Boolean = False) 'API to display a userform in THIS workbook, from another workbook On Error Resume Next UserForm1.Show IIF(Modal,vbModal,vbModeless) ShowTheForm = (Err.Number = 0) End Function 

然后,在试图打开此窗体的工作簿中,您将需要调用ShowTheForm过程,如下所示:

 Do While file <> "" Set wb = Application.Workbooks.Open(file) If Not IsEmpty(wb) Then Application.Visible = False Application.Run("'" & wb.Name & "'!Module1.ShowTheForm") End If wb.Close file = Dir() Loop 

由于您已将ShowTheForm作为具有返回值的函数提供,因此可以捕获错误,例如:

 If Not Application.Run("'" & wb.Name & "'!Module1.ShowTheForm") Then MsgBox "Unable to display..." Exit Sub End If 

根据此处提供的一般逻辑进行修改/增强:

http://answers.microsoft.com/en-us/office/forum/office_2007-excel/how-do-you-open-userform-in-another-workbook/e97b2c06-2a79-4cef-89bc-4f67b0f3c03a?db= 5&AUTH = 1

注意

我认为IsEmpty不是对工作簿对象的适当testing,您可能需要考虑这一点。 我不确定你想要做什么,但是我几乎可以肯定,它不是在做你认为正在做的事情。

我认为这就是你正在寻找,如何从工作簿引用UserForm

 Workbooks("Book1.xls").VBProject.VBComponents.Item("UserForm1") 

这是工作,但我不能设法使用.Show方法:

 Sub UFtest() Dim UF_test As Object Set UF_test = ThisWorkbook.VBProject.VBComponents.Item("UserForm1") UF_test.Show End Sub 

这里是你的完整代码:

 Private Sub Workbook_OnClick() Dim mypath As String Dim file As String Dim wb As Workbook Dim pat As String Application.ScreenUpdating = False ChDrive "C:" ChDir "C:\Users\Administrator\Desktop\John" 'john is a folder that consists of the excel files mypath = Range("B1").Value 'mypath has the same value as chDir file = Dir(mypath & "\" & "*.xlsx") Do While file <> "" Set wb = Application.Workbooks.Open(file) If Not IsEmpty(wb) Then Application.Visible = False wb.VBProject.VBComponents.Item("UserForm1").Show End If wb.Close file = Dir() Loop End Sub