宏以打开“另存为”窗口并自动填充文件名和类型

时间:2018-06-15 20:14:28

标签: vba excel-vba excel

为了帮助加快保存审计表的过程,有一个命名约定,并且已在工作簿中具有Defined Name savefile_nameSave As的参考工作表中处理。

但是,审计表保存在现场的各种计算机上,并且一旦返回办公室,最终会由每个用户迁移到存档中。因此,我希望我的宏打开.xlsm对话框,填充名称并选择xlOpenXMLWorkbookMacroEnabledSave As(Excel宏启用工作簿)格式。

我当前的代码inspired by this post将很乐意打开.xlsm对话框并填充名称,但不会选择Save As格式;它始终具有最后一种格式,就像上次打开Dim FileName As String FileName = Range("savefile_name").Value Dim fPth As Object Set fPth = Application.FileDialog(msoFileDialogSaveAs) With fPth .InitialFileName = FileName & ".xlsm" .Title = "Save your File" .InitialView = msoFileDialogViewList If .Show <> 0 Then ThisWorkbook.SaveAs FileName:=.SelectedItems(1), FileFormat:=xlOpenXMLWorkbookMacroEnabled End If End With 对话框时一样。如何阻止这种情况发生?

我的VBA代码:

npm i

2 个答案:

答案 0 :(得分:3)

.FilterIndex = 2声明中添加with

此外,根据您使用的Excel版本,您可能无需将& ".xlsm"添加到.InitialFileName的末尾。如果您想了解更多有关如何查找其他扩展的详细信息,请在代码中使其更具变量;你可以查看答案here.

Dim FileName As String
FileName = Range("savefile_name").Value

Dim fPth As Object
Set fPth = Application.FileDialog(msoFileDialogSaveAs)

With fPth
  .InitialFileName = FileName
  .Title = "Save your File"
  .FilterIndex = 2
  .InitialView = msoFileDialogViewList
  If .Show <> 0 Then
    ThisWorkbook.SaveAs FileName:=.SelectedItems(1), FileFormat:=xlOpenXMLWorkbookMacroEnabled
  End If
End With

答案 1 :(得分:2)

尝试这种方式,我有同样的问题要保存在.xlsm中并且它在Excel 2013上工作:

Dim FileName As String
FileName = Range("savefile_name").Value

Dim fname As Variant
fname = Application.GetSaveAsFilename(fileFilter:="Excel Marcro-Enabled Workbook (*.xlsm),*.xlsm", _
InitialFileName:=FileName, _
Title:="Save your File")
If fname = False Then Exit Sub  'Exit if user hit Cancel
ThisWorkbook.SaveAs FileName:=fname, FileFormat:=52