首页 > 解决方案 > 选择前一个文件夹的文件夹对话框

问题描述

我正在尝试使用文件对话框来选择稍后将在代码中使用的文件夹。以下内容用作调用其他几个宏并将各种其他用户输入作为字符串的 Userform 的一部分。

这个宏应该做的(稍后在代码中)是将文件导出到用户使用此fldrpicker对话框指定的文件夹。问题是这样的:文件导出到我想要的文件夹之前的文件夹,我不知道为什么。

`Public FilePath as String
Private Sub folderpicker_click() 'A field in the UserForm
Application.EnableCancelKey = xlDisabled
    Dim fldr As FileDialog, sItem As String
    Set fldr = Application.FileDialog(msoFileDialogFolderPicker)
    With fldr
        .Title = "Select a Folder"
        .AllowMultiSelect = False
        .InitialFileName = "\\user\Desktop\Folder1\Folder2\Folder3\"
        If .Show <> -1 Then GoTo NextCode
        sItem = .SelectedItems(1)
    End With
FilePath = fldr.InitialFileName
NextCode:
    GetFolder = sItem
    Set fldr = Nothing
DestinationFolder.Value = sItem
End Sub
`

使用此代码,文件将保存,Folder2Folder3不像我需要的那样。我尝试使用msgbox(FilePath)在此运行后立即使用的临时子进行故障排除,但它告诉我,FilePath所以\\user\Desktop\Folder1\Folder2\我认为错误不是导出它(这就是我没有包含那段代码的原因)。

标签: excelvba

解决方案


我相信发生的事情是因为您使用的是 FilePath = fldr.InitialFileName,它本质上是对话中选择的原始文件夹,如果您将代码更改为此它应该可以按预期工作:

Sub foo()
Application.EnableCancelKey = xlDisabled
    Dim fldr As FileDialog, sItem As String
    Set fldr = Application.FileDialog(msoFileDialogFolderPicker)
    With fldr
        .Title = "Select a Folder"
        .AllowMultiSelect = False
        .InitialFileName = "\\user\Desktop\Folder1\Folder2\Folder3\"
        If .Show <> -1 Then GoTo NextCode
        sItem = .SelectedItems(1)
    End With
FilePath = sItem
NextCode:
    GetFolder = sItem
    Set fldr = Nothing
DestinationFolder.Value = sItem
End Sub

推荐阅读