文件夹选择器Excel VBA并将粘贴路径粘贴到单元格

时间:2018-11-01 17:12:35

标签: excel vba excel-vba path filedialog

我很难弄清楚如何将文件夹路径放入单元格C49中。我想在那里找到路径,以便用户了解他们在哪里搜索以及是否必须更改所说的路径。

我从这里获得了VBA代码, http://learnexcelmacro.com/wp/2016/12/how-to-open-file-explorer-in-vba/

Private Sub cmd_button_BROWSEforFolder_Click()

    On Error GoTo err
    Dim fileExplorer As FileDialog
    Set fileExplorer = Application.FileDialog(msoFileDialogFolderPicker)

    'To allow or disable to multi select
    fileExplorer.AllowMultiSelect = False

    With fileExplorer
        If .Show = -1 Then 'Any folder is selected
            [folderPath] = .SelectedItems.Item(1)
            ThisWorkbook.Sheets("Home").Range("C49") = .SelectedItems.Item(1)
        Else ' else dialog is cancelled
            MsgBox "You have cancelled the dialogue"
            [folderPath] = "" ' when cancelled set blank as file path.
        End If
        End With
err:
    Exit Sub

End Sub

我尝试重新排列位置,

ThisWorkbook.Sheets("Home").Range("C49") = .SelectedItems.Item(1)

并尝试更改

.SelectedItems.Item(1)

至     [folderPath] 没有胜利。

我想念什么? 我需要的只是要在txtbox上方显示的路径,如果需要更改它,则用户可以使用按钮来重定向搜索。 (此按钮将不会启动搜索宏) enter image description here

1 个答案:

答案 0 :(得分:2)

Private Sub cmd_button_BROWSEforFolder_Click()

    On Error GoTo err
    Dim fileExplorer As FileDialog
    Set fileExplorer = Application.FileDialog(msoFileDialogFolderPicker)
    Dim folderPath As String

    'To allow or disable to multi select
    fileExplorer.AllowMultiSelect = False

    With fileExplorer
        If .Show = -1 Then 'Any folder is selected
            folderPath = .SelectedItems.Item(1)

        Else ' else dialog is cancelled
            MsgBox "You have cancelled the dialogue"
            folderPath = "NONE" ' when cancelled set blank as file path.
        End If
    End With
err:

ThisWorkbook.Sheets("Home").Range("C49") = folderPath

End Sub