如何在用户表单

时间:2018-05-15 12:50:33

标签: vba userform

在vba用户表单中,我提示用户提出几个问题。我坚持一个特别的提示。我不知道如何在用户表单中包含msoFileDialogFolderPicker的提示。
我使用了与下面列出的功能类似的代码作为单独的弹出窗口,但我不知道如何将其放在用户窗体中。这可能吗?

Function GetFolder() As String
    Dim fldr As FileDialog
    Dim sItem As String
    Set fldr = Application.FileDialog(msoFileDialogFolderPicker)
    With fldr
        .Title = "Select a Folder"
        .AllowMultiSelect = False
        .InitialFileName = Application.DefaultFilePath
        If .Show <> -1 Then GoTo NextCode
        sItem = .SelectedItems(1)
    End With
NextCode:
    GetFolder = sItem
    Set fldr = Nothing
End Function

感谢您查看此内容。

1 个答案:

答案 0 :(得分:1)

首先创建一个模块(在VBA窗口中,左窗格,右键单击,插入...,模块)。然后在此模块中移动您的函数GetFolder(),声明为public

Option Explicit

Public Function GetFolder() As String
    Dim fldr As FileDialog
    Dim sItem As String
    Set fldr = Application.FileDialog(msoFileDialogFolderPicker)
    With fldr
        .Title = "Select a Folder"
        .AllowMultiSelect = False
        .InitialFileName = Application.DefaultFilePath
        If .Show <> -1 Then GoTo NextCode
        sItem = .SelectedItems(1)
    End With
NextCode:
    GetFolder = sItem
    Set fldr = Nothing
End Function

然后在您的表单中,您需要一些可以调用该过程的内容。通常我们用按钮来做。

因此,在表单中添加一个按钮。然后双击按钮(或右键单击“代码”),它将为它创建一个单击事件。

在按钮事件代码中,调用GetFolder程序:

Option Explicit

Private Sub CommandButton1_Click()
    Dim strFolder As String

    strFolder = GetFolder()

    MsgBox strFolder

End Sub