获取另存为文件名
- 你的代码的明星是Application.GetSaveAsFilename 方法
(Excel)|微软
文档 https://learn.microsoft.com/en-us/office/vba/api/excel.application.getsaveasfilename.
三句话
问题
The Code
Option Explicit
' Gets the extension (the string behind the last dot) of a filename.
Function getExtension(ByVal fName As String) As String
getExtension = LCase(Right(fName, Len(fName) - InStrRev(fName, ".")))
End Function
' DisplayAlerts Version
Sub getSaveFileDA()
Dim fName As Variant
Dim FileFormatValue As Long
With Application
fName = .GetSaveAsFilename( _
InitialFileName:=Range("O26").Value, FileFilter:= _
" Excel Macro Free Workbook (*.xlsx), *.xlsx," & _
" Excel Macro Enabled Workbook (*.xlsm), *.xlsm," & _
" Excel 2000-2003 Workbook (*.xls), *.xls," & _
" Excel Binary Workbook (*.xlsb), *.xlsb", _
FilterIndex:=4, Title:="Save as .xlsb")
End With
' Find the correct FileFormat that matches the choice
' in the "Save as type" list.
Select Case getExtension(fName)
Case "xls": FileFormatValue = 56
Case "xlsx": FileFormatValue = 51
Case "xlsm": FileFormatValue = 52
Case "xlsb": FileFormatValue = 50
Case Else: FileFormatValue = 0
End Select
If fName = False Then ' When user selects Cancel.
MsgBox "Project Not Saved!"
Exit Sub
End If
' If fName exists then Excel will complain about it and when you
' press No or Cancel, an error will occur. To prevent this you can
' use Application.DisplayAlerts but keep in mind that then the file
' will be overwritten without the confirmation dialog popping up.
Application.DisplayAlerts = False
ActiveWorkbook.SaveAs fName, FileFormat:= _
FileFormatValue, CreateBackup:=False
Application.DisplayAlerts = True
MsgBox "Project successfully saved.", vbInformation
End Sub
' On Error Resume Next Version
Sub getSaveFileOE()
Dim fName As Variant
Dim FileFormatValue As Long
With Application
fName = .GetSaveAsFilename( _
InitialFileName:=Range("O26").Value, FileFilter:= _
" Excel Macro Free Workbook (*.xlsx), *.xlsx," & _
" Excel Macro Enabled Workbook (*.xlsm), *.xlsm," & _
" Excel 2000-2003 Workbook (*.xls), *.xls," & _
" Excel Binary Workbook (*.xlsb), *.xlsb", _
FilterIndex:=4, Title:="Save as .xlsb")
End With
' Find the correct FileFormat that matches the choice
' in the "Save as type" list.
Select Case getExtension(fName)
Case "xls": FileFormatValue = 56
Case "xlsx": FileFormatValue = 51
Case "xlsm": FileFormatValue = 52
Case "xlsb": FileFormatValue = 50
Case Else: FileFormatValue = 0
End Select
If fName = False Then GoTo NotSaved ' When user selects Cancel.
On Error Resume Next
ActiveWorkbook.SaveAs fName, FileFormat:= _
FileFormatValue, CreateBackup:=False
If Err.Number <> 0 Then
On Error GoTo 0
GoTo NotSaved
Else
On Error GoTo 0
MsgBox "Project successfully saved.", vbInformation
End If
Exit Sub
NotSaved:
MsgBox "Project Not Saved!", vbExclamation
End Sub