2017-09-25 106 views
0

我试图使用filedialog.show函数获取文件夹的路径。VBA FileDialog.Show重新启动子

我现在面临的问题是:

  • 后,我选择在folderpicking窗口中的代码不会继续的文件夹。它可以重新启动,也可以在没有任何事情发生时结束

可能是什么问题?

[...] 

Dim fpath As Variant 
Dim fldr As Object 
Set fldr = Application.FileDialog(msoFileDialogFolderPicker) 
fldr.Title = "Select a Folder" 
fldr.AllowMultiSelect = False 
fldr.InitialFileName = Application.DefaultFilePath 
If fldr.Show = -1 Then 
    fpath = fldr.SelectedItems(1) 
Else 
    GoTo NextCode 
End If 
NextCode: 
set fldr = Nothing 

[...] 
+0

代码适用于我。这个错误可能在于你显示为'[...]'的部分,这让你有点难以帮助你。 – YowE3K

回答

1

它的工作原理,你只是不使用它来显示路径结果(或从本Sub返回String值)。

更改代码:

If fldr.Show = -1 Then 
    fpath = fldr.SelectedItems(1) 
Else 
    GoTo NextCode 
End If 

NextCode: 
set fldr = Nothing 

要:

If fldr.Show = -1 Then 
    fpath = fldr.SelectedItems(1) 
    MsgBox fpath ' <-- for DEBUG 
End If 

Set fldr = Nothing 

如果你想用你的代码作为一个Function返回所选文件夹的路径,使用下面的代码:

Function GetFolderPath() As String 

Dim fpath As Variant 
Dim fldr As Object 

Set fldr = Application.FileDialog(msoFileDialogFolderPicker) 
With fldr 
    .Title = "Select a Folder" 
    .AllowMultiSelect = False 
    .InitialFileName = Application.DefaultFilePath 

    If .Show = -1 Then 
     GetFolderPath = .SelectedItems(1) 
    End If 
End With  
Set fldr = Nothing 

End Function 

Sub代码来测试它:

Sub Test() 

Dim FolderPath As String 

FolderPath = GetFolderPath 
MsgBox FolderPath 

End Sub 
+0

显然确实代码工作正常。只是因为我正在使用调试“步入”,并且它已经丢失。我使用MsgBox作为检查点,并在代码中进一步细分,并且顺利进行。 –