我正在尝试使用文件对话框来选择稍后将在代码中使用的文件夹。以下内容用作调用其他几个宏并将各种其他用户输入作为字符串的用户窗体的一部分。
此宏应该执行的操作(稍后在代码中(是将文件导出到用户使用此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 = "\userDesktopFolder1Folder2Folder3"
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
我需要它。我尝试使用一个临时 sub 进行故障排除,该 sub 在此运行后立即使用msgbox(FilePath)
,但它告诉我FilePath
\userDesktopFolder1Folder2
,所以我认为错误不会导出它(这就是为什么我没有包含那段代码(。
我相信正在发生的事情是因为您使用的是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 = "\userDesktopFolder1Folder2Folder3"
If .Show <> -1 Then GoTo NextCode
sItem = .SelectedItems(1)
End With
FilePath = sItem
NextCode:
GetFolder = sItem
Set fldr = Nothing
DestinationFolder.Value = sItem
End Sub