简体   繁体   中英

Excel VBA: open fixed file path but not fixed file name

I want to write a code that will open the file path and within this folder the user can select his own folder. I only seem able to find a " general" code to open a folder.

With wbtarget.Sheets("Data")
    strPathName = Application.GetOpenFilename()      
    If strPathName = "False" Then
       Exit Sub
    End If        
    Set wbsource = Workbooks.Open(strPathName, 0)
    .Range("A1:AL10000").Value = wbsource.Sheets(1).Range("A1:AL10000").Value
    wbsource.Close (False)
End With

or open a specific file.

folder_path = CStr("C:\Users\peter\Documents\me")
file_name = CStr("report.xlsm")
StrResource = folder_path & "\" & file_name

thank you for your help.

I use this function to let the user browse for a folder instead of a file. I don't remember where I found it.
It uses the Shell.BrowseForFolder method.

Set InitPath to a string <> "", eg "D:\\Files", to limit the folder tree the user can choose from.

Public Function GetFolderName(Caption As String, InitPath As String) As String

    Dim AppShell As Object
    Dim BrowseDir As Variant
    Dim sPath As String

    Set AppShell = CreateObject("Shell.Application")
    If InitPath <> "" Then
        Set BrowseDir = AppShell.BrowseForFolder(0, Caption, &H11, (InitPath))
    Else
        ' 17 = root folder is "My Computer"
        Set BrowseDir = AppShell.BrowseForFolder(0, Caption, &H11, 17)
    End If

    sPath = ""
    On Error Resume Next
    sPath = BrowseDir.Items().Item().Path
    GetFolderName = sPath

End Function

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM