2017-09-25 107 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作爲檢查點,並在代碼中進一步細分,並且順利進行。 –