获取VBA保存对话框的文件名和目的地

我目前已经设置了一个对话框,允许用户select一个文件的目的地。 select目的地后,您可以input文件的名称,并将“FileSaveName”设置为像C:\user\desktop\test.xml这样的完整pathC:\user\desktop\test.xml我是通过VBA提供的此工具的新手。 是否可以分别获取文件名和扩展名? 或者我需要手动修剪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 

您可以使用Windows脚本对象:

 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 

这里很好的参考

你可以这样做

 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