如何在用户窗体中包含 msoFileDialogFolderPicker

How to include msoFileDialogFolderPicker in a 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

感谢您的关注。

首先创建一个模块(在 VBA window,左窗格中,右键单击,插入...,模块)。然后在这个模块中移动你的函数 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

然后在您的表单中,您需要一些可以调用该过程的东西。通常我们用一个按钮来做到这一点。

因此,向表单添加一个按钮。然后双击按钮(或者右击"code"),它会为它创建一个点击事件。

在按钮事件代码中,调用您的 GetFolder 过程:

Option Explicit

Private Sub CommandButton1_Click()
    Dim strFolder As String

    strFolder = GetFolder()

    MsgBox strFolder

End Sub