你如何获得文件名而不是打开文件的整个文件路径?

sta*_*tor 1 excel filenames vba getopenfilename

换句话说,在调用Application.GetOpenFileName()Method 之后我需要进行一些字符串处理吗?

Jea*_*ett 10

为什么要重新发明轮子并写出大量的样板代码?只需使用现有的FileSystemObject的GetFileName方法,该方法已经为您编写并测试和调试:

filename = FSO.GetFileName(path)
Run Code Online (Sandbox Code Playgroud)

这是一个有效的例子:

Dim path As String
Dim filename As String
Dim FSO As Scripting.FileSystemObject
Set FSO = New FileSystemObject

path = "C:\mydir\myotherdir\myfile.txt"

filename = FSO.GetFileName(path) 'Bingo. Done.

Debug.Print filename ' returns "myfile.txt"

' Other features:
Debug.Print FSO.GetBaseName(path) ' myfile
Debug.Print FSO.GetExtensionName(path) ' txt
Debug.Print FSO.GetParentFolderName(path) ' C:\mydir\myotherdir
Debug.Print FSO.GetDriveName(path) ' C:
' et cetera, et cetera.
Run Code Online (Sandbox Code Playgroud)

您需要按如下方式设置引用:工具>引用...>在Microsoft Scripting Runtime旁边设置复选标记.

否则使用后期绑定:

Dim FSO As Object
Set FSO = CreateObject("Scripting.FileSystemObject")
Run Code Online (Sandbox Code Playgroud)


Oli*_*bes 5

我正在使用这些函数进行文件名处理.最后一个是你需要的那个.

Public Function FilePathOf(ByVal s As String) As String
    Dim pos As Integer

    pos = InStrRev(s, "\")
    If pos = 0 Then
        FilePathOf = ""
    Else
        FilePathOf = Left$(s, pos)
    End If
End Function

Public Function FileNameOf(ByVal s As String) As String
    Dim pos1 As Integer, pos2 As Integer

    pos1 = InStrRev(s, "\") + 1
    pos2 = InStrRev(s, ".")
    If pos2 = Len(s) Then pos2 = pos2 + 1
    If pos2 = 0 Then pos2 = Len(s) + 1
    FileNameOf = Mid$(s, pos1, pos2 - pos1)
End Function

Public Function FileExtOf(ByVal s As String) As String
    Dim pos As Integer

    pos = InStrRev(s, ".")
    If pos = 0 Then
        FileExtOf = ""
    Else
        FileExtOf = Mid$(s, pos + 1)
    End If
End Function

Public Function FileNameExtOf(ByVal s As String) As String
    FileNameExtOf = Mid$(s, InStrRev(s, "\") + 1)
End Function
Run Code Online (Sandbox Code Playgroud)

  • 为什么要重新发明轮子并编写大量样板代码?只需使用现有的 FileSystemObject ... (2认同)