要获得文件名和扩展名,可以同时使用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 = A(, , "选择源文件")
If sFileName = "False" Then Exit Sub '用户选择"取消"则退出程序
aRet = SplitFilename(sFileName)
MsgBox "路径:" & aRet(1) & vbNewLine & _
"文件名:" & aRet(2) & vbNewLine & _
"扩展名:" & aRet(3)
End Sub
运行上述代码后,按照打开的对话框选择目标文件后,即可显示下面的信息框:
2 使用FSO对象模型拆分文件名和扩展名
Sub FSO分离文件名()
Dim fso As New FileSystemObject, sFileName As String
Dim str1 As String
sFileName = A(, , "选择源文件")
If sFileName = "False" Then Exit Sub
MsgBox "路径:" & (sFileName) & vbNewLine & _
"文件名:" & (sFileName) & vbNewLine & _
"扩展名:" & (sFileName)
Set fso = Nothing
End Sub
-End-