I currently have set up a dialog box which will allow a user to pick a file destination. After the destination is picked, you can input a name of the file, and will set "FileSaveName" to the full path like C:\\user\\desktop\\test.xml
I am new to this tool that is offered through VBA. Is it possible to obtain the file name and the extension separately? Or will I need to manually trim characters from the string?
fileSaveName = Application.GetSaveAsFilename( _
fileFilter:="Text Files (*.xml), *.xml")
If fileSaveName <> False Then
MsgBox "File path and file name: " & fileSaveName
'MsgBox "File path: " & filepath
'MsgBox "File name: " & filename
End If
You can use the Windows Scripting objects:
Dim objFS as Object
Dim objFile as Object
Dim strPath as String
Dim strFile as String
Dim strExt as String
fileSaveName = Application.GetSaveAsFilename( _
fileFilter:="Text Files (*.xml), *.xml")
If fileSaveName <> False Then
MsgBox "File path and file name: " & fileSaveName
Set objFS = CreateObject("Scripting.FileSystemObject")
Set objFile = objFSO.GetFile(fileSaveName)
strFile = objFile.Name
strPath = objFile.ParentFolder
strExt = objFS.GetExtensionName(fileSaveName)
MsgBox "File path: " & strPath
MsgBox "File name: " & strFile
MsgBox "File extension: " & strExt
' Remove references
Set objFile = Nothing
Set objFS = Nothing
End If
you could do like this
Sub main()
Dim fileSaveName As Variant
fileSaveName = Application.GetSaveAsFilename( _
fileFilter:="Text Files (*.xml), *.xml")
If fileSaveName <> False Then
MsgBox "File path and file name: " & fileSaveName
MsgBox "File path: " & GetFilePath(fileSaveName)
MsgBox "File name: " & GetFileName(fileSaveName)
MsgBox "File extension: " & GetFileExt(fileSaveName)
End If
End Sub
Function GetFilePath(fileFullPath As Variant) As String
GetFilePath = Left(fileFullPath, InStrRev(fileFullPath, "\"))
End Function
Function GetFileName(fileFullPath As Variant) As String
GetFileName = Right(fileFullPath, Len(fileFullPath) - InStrRev(fileFullPath, "\"))
End Function
Function GetFileExt(fileFullPath As Variant) As String
Dim fileName As String
fileName = GetFileName(fileFullPath)
GetFileExt = Right(fileName, Len(fileName) - InStrRev(fileName, "."))
End Function
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.