文件夹资源管理器在Excel VBA中不能正常工作

时间:2018-01-02 08:28:11

标签: excel vba

Private Sub ButtonPath_Click()
    Cells(1, 32).Value = FolderExplorer()
End Sub

以上是我的UserForm代码。 Code下面是My Module的FolderExplorer()函数。

'//Source : http://software-solutions-online.com/vba-folder-dialog/ , edited by me.
Public Function FolderExplorer()
    Dim intResult As Integer
    Dim strPath As String
    Application.FileDialog(msoFileDialogFolderPicker).ButtonName _
    = "Select Path"
    'the dialog is displayed to the user
    intResult = Application.FileDialog(msoFileDialogFolderPicker).Show
    'checks if user has cancled the dialog.
    If intResult <> 0 Then
        'dispaly message box
        'Call MsgBox(Application.FileDialog(msoFileDialogFolderPicker _
        ).SelectedItems(1), _
        vbInformation, "Selected Folder")
        FolderExplorer() = Application.FileDialog(msoFileDialogFolderPicker).SelectedItems(1)
    End If
End Function

起初看起来效果很好。当我按下userform中的按钮时,FolderExplorer会弹出。但是当我选择文件夹路径时,文件夹浏览器会再次弹出,当我选择文件夹路径时,文件夹资源管理器会再次弹出....永远。

我的代码中没有循环。我该如何解决这个问题?

提前感谢您的回答。

1 个答案:

答案 0 :(得分:0)

您正在FolderExplorer()递归调用FolderExplorer() = Application.FileDialog(msoFileDialogFolderPicker).SelectedItems(1)

您应该使用FolderExplorer = Application.FileDialog(msoFileDialogFolderPicker).SelectedItems(1)来返回值。

以下是您的代码的简化版本。

Public Function FolderExplorer()
    Dim intResult As Integer
    Dim strPath As String

    With Application.FileDialog(msoFileDialogFolderPicker)
        .ButtonName = "Select Path"
        intResult = .Show
        If intResult <> 0 Then
            FolderExplorer = .SelectedItems(1)
        End If
    End With
End Function