首页 > 解决方案 > Excel VBA通​​过用户窗体选择后保存文件夹位置

问题描述

我试图为用户提供“设置”默认文件夹位置的选项,这仅用于预填充更多用户表单文本框,以节省时间msoFileDialogFolderPicker

我确实使用了 chdir,但它已写入 vba 脚本,此位置因用户而异,并且只需要在插件安装时设置一次

这是主文件夹选择器的代码:

Private Sub cmdfoldsel_Click()
    On Error GoTo err
    Dim fileExplorer As FileDialog
    Set fileExplorer = Application.FileDialog(msoFileDialogFolderPicker)

    'To allow or disable to multi select
    fileExplorer.AllowMultiSelect = False

    With fileExplorer
        If .Show = -1 Then 'Any folder is selected
            tbmasterloc.text = .SelectedItems.Item(1)
        Else ' else dialog is cancelled
            MsgBox "You have cancelled the dialogue"
            [folderPath] = "" ' when cancelled set blank as file path.
        End If
    End With
err:
    Exit Sub
End Sub

它让我选择文件夹,但显然当我关闭时文本会消失(我使用的是关闭按钮,unload me但我认为这是删除文本

将调用该文件夹位置的第二个用户窗体的示例如下:

Private Sub UserForm_Initialize()
    copyfromtb.Value = mfs.tbmasterloc.text
End Sub
Private Sub copyfromcmd_Click()

    Dim fldr As FileDialog
    Dim sItem As String

    Set fldr = Application.FileDialog(msoFileDialogFolderPicker)
    
    With fldr
        .Title = "Select a Folder"
        .AllowMultiSelect = False
        .InitialFileName = Application.DefaultFilePath
        '.InitialFileName = Application.GetSaveAsFilename()
        If .Show <> -1 Then GoTo NextCode
        sItem = .SelectedItems(1)
    End With
NextCode:
    GetFolder = sItem
    copyfromtb.Value = sItem

    Set fldr = Nothing


End Sub

标签: excelvba

解决方案


推荐阅读