How do you get just the filename rather than the entire file path of an open file?

前端 未结 5 1427
遥遥无期
遥遥无期 2020-12-06 23:07

In other words, would I need to do some string processing after invoking the Application.GetOpenFileName() Method?

5条回答
  •  再見小時候
    2020-12-06 23:47

    In this case, you are using Application.GetOpenFilename(), so you are sure that file physically exists on disk, so the simplest approach will be to use Dir().

    fileName = Dir(filePath)
    

    Full code is:

    Dim fileName, filePath As Variant
    
    filePath = Application.GetOpenFilename("Excel files (*.xlsm), *.xlsm", , "Select desired file", , False)
    
    If filePath = False Then
        MsgBox "No file selected.", vbExclamation, "Sorry!"
        Exit Sub
    Else
    
        'Remove path from full filename
        fileName = Dir(filePath)
    
        'Print file name (with extension)
        MsgBox "File selected." & vbCr & vbCr & fileName, vbInformation, "Sucess!"
    
    End If
    

提交回复
热议问题