我正在尝试使用文件对话框来选择稍后将在代码中使用的文件夹。以下内容用作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
`
使用此代码,该文件将保存在Folder2
而不是Folder3
,就像我需要它一样。我试图在运行后立即使用msgbox(FilePath)
的临时子进行故障排除,但它告诉我FilePath
是\\user\Desktop\Folder1\Folder2\
所以我不认为错误正在导出它(这就是为什么我还没有包含那段代码)。
答案 0 :(得分:0)
我相信正在发生的事情是因为您使用的是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