OpenFileDialog in vba that returns the directory as a string

自闭症网瘾萝莉.ら 提交于 2019-12-10 09:27:43

问题


I have been looking everywhere and I am very surprised that this is not already easily available as a function in VBA.

I need a function that when called, opens a filedialog where people can select 1 file (not more, just 1) and then the function returns the location of the file (including filename+extension) as a string.

At first i thought: " How hard can that be, I'ts really simple in VB.NET.."

Thanks in advance!


回答1:


You mean like htis?

Sub Sample()
    Dim ofD As Object
    Dim Fil

    Set ofD = Application.FileDialog(3)

    ofD.AllowMultiSelect = False
    ofD.Show

    For Each Fil In ofD.SelectedItems
        MsgBox Fil
    Next
End Sub

The above For loop is useful if AllowMultiSelect is True

Here is another example if there is only one file.

Sub Sample()
    Dim ofD As Object
    Dim Fil

    Set ofD = Application.FileDialog(3)

    ofD.AllowMultiSelect = False

    If ofD.Show = False Then
        MsgBox "User Pressed Cancel"
    Else
        MsgBox ofD.SelectedItems(1)
    End If
End Sub



回答2:


I had the same problem earlier this week here the solution I used.

http://www.mrexcel.com/forum/excel-questions/294728-browse-folder-visual-basic-applications.html

Hope it help you too.



来源:https://stackoverflow.com/questions/15971619/openfiledialog-in-vba-that-returns-the-directory-as-a-string

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!