如何从vba中的path中提取文件名

我正在写一个代码,在这里我打开一个文件来提取数据。 我目前使用下面的代码; 我想从path中提取文件名并将其存储在特定范围内。 这个代码:

FilePath = Application.GetOpenFilename("Excel Files (*.xlsx), *.xls") If FilePath <> False Then Range("D6").Value = FilePath file = Range("D6").Value Range("D6").Clear End If 

你可以像下面这样做:

 FilePath = Application.GetOpenFilename("Excel Files (*.xlsm), *.xlsm") If FilePath <> False Then Dim fso As Object Dim objFile As Object Set fso = VBA.CreateObject("Scripting.FileSystemObject") Set objFile = fso.GetFile(FilePath) If Not objFile Is Nothing Then FileName = objFile.Name End If End If 

替代:

 Public Function ExtractFileName(ByVal strFullName As String) As String Dim p As Integer Dim i As Integer Dim s As Integer i = 1 Do p = InStr(i, strFullName, "\", 1) If p = 0 Then Exit Do s = p i = p + 1 Loop s = s + 1 ExtractFileName = Mid(strFullName, s, Len(strFullName)) End Function 'ExtractFileName 

最简单的方法:

 FileName = Mid$(FilePath, InStrRev(FilePath, "\") + 1, Len(FilePath))