从另一个文件中调用UserForm

时间:2015-11-20 09:42:59

标签: excel vba excel-vba userform multiple-files

  

将调用一个Excel文件的UserForm的VBA代码写入名为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文件中提取UserForm,而不是john文件夹中的Excel文件。

2 个答案:

答案 0 :(得分:2)

包含要显示的UserForm的工作簿还应具有显示表单的过程。您需要调用过程来显示userform。它可以是函数或子函数,我更喜欢函数,因为那样你就可以返回错误处理的成功/失败。

在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不是对工作簿对象的适当测试,您可能希望查看它。我不确定你在尝试用这条线做什么,但我几乎可以肯定它并没有做你认为它做的事情。

答案 1 :(得分:1)

我认为这就是您要找的,如何从工作簿中引用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