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

问题描述 投票:1回答:1
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会弹出。但是当我选择文件夹路径时,文件夹资源管理器再次弹出,当我选择文件夹路径时,文件夹资源管理器再次弹出....永远。

我的代码中没有循环。我怎么解决这个问题?

谢谢你提前回答。

excel vba
1个回答
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
© www.soinside.com 2019 - 2024. All rights reserved.