如何从vba中的路径中提取文件名

时间:2015-08-18 07:23:16

标签: excel vba excel-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

4 个答案:

答案 0 :(得分:3)

你可以这样做:

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

答案 1 :(得分:2)

替代方案:

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

答案 2 :(得分:1)

最简单的方法:

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

答案 3 :(得分:0)

如果您想要各种版本的路径和文件名,这是我的建议:

Sub LookupFileNames()
  Dim FilePath As String, FileOnly As String, PathOnly As String, ExtOnly As String, NameOnly As String

  FilePath = ThisWorkbook.FullName
  FileOnly = ThisWorkbook.Name
  NameOnly = Left(FileOnly, InStr(1, FileOnly, ".") - 1)
  ExtOnly = Right(FileOnly, Len(FileOnly) - InStr(1, FileOnly, "."))
  PathOnly = Left(FilePath, Len(FilePath) - Len(FileOnly))

  MsgBox "Full Name: " & FilePath & vbLf & "File Name: " & FileOnly & vbLf & "File Name w/o Ext: " & NameOnly & vbLf & "File Ext: " & ExtOnly & vbLf & "File Path: " & PathOnly

End Sub