Как извлечь имя файла из его пути в vba
Я пишу код, где я открываю файл для извлечения данных. В настоящее время я использую следующий код; Я хочу извлечь имя файла из пути и сохранить его в определенном диапазоне. Этот код:
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))