VBA|文件处理04:获取文件名和扩展名-文件名后缀

要获取文件名和扩展名,可以使用VBA语句和FSO对象模型两种方式。

1 使用VBA语句拆分文件名和扩展名

Function SplitFilename(ByVal sFileName As String) As Variant

Dim aRet(1 To 3) As String

Dim i As Integer

i = InStrRev(sFileName, "\")

aRet(1) = Left(sFileName, i)

sFileName = Mid(sFileName, i + 1)

i = InStrRev(sFileName, ".")

aRet(2) = Left(sFileName, i - 1)

aRet(3) = Mid(sFileName, i + 1)

SplitFilename = aRet

End Function

Sub 分离文件名()

Dim sFileName As String, aRet As Variant

sFileName = Application.GetOpenFilename(, , "选择源文件")

If sFileName = "False" Then Exit Sub '用户选择"取消"则退出程序

aRet = SplitFilename(sFileName)

MsgBox "路径:" & aRet(1) & vbNewLine & _

"文件名:" & aRet(2) & vbNewLine & _

"扩展名:" & aRet(3)

End Sub

运行上述代码后,按照打开的对话框选择目标文件后,即可显示下面的信息框:

VBA|文件处理04:获取文件名和扩展名

2 使用FSO对象模型拆分文件名和扩展名

Sub FSO分离文件名()

Dim fso As New FileSystemObject, sFileName As String

Dim str1 As String

sFileName = Application.GetOpenFilename(, , "选择源文件")

If sFileName = "False" Then Exit Sub

MsgBox "路径:" & fso.GetParentFolderName(sFileName) & vbNewLine & _

"文件名:" & fso.GetBaseName(sFileName) & vbNewLine & _

"扩展名:" & fso.GetExtensionName(sFileName)

Set fso = Nothing

End Sub

-End-

推荐阅读