另存为对话框的excel代码

我在网上find了这段代码,打开另存为对话框到驱动器上的位置,并让用户保存文件。 当你点击“保存”时,文件不会保存。 我不知道我在这里做错了什么。 帮帮我?

这是有问题的代码:

Dim varResult As Variant 'displays the save file dialog varResult = Application.GetSaveAsFilename(FileFilter:= _ "Excel Files (*.xlsx), *.xlsx", Title:="Save PO", _ InitialFileName:="\\showdog\service\Service_job_PO\") 'checks to make sure the user hasn't canceled the dialog If varResult <> False Then Exit Sub End If 

你必须明确告诉Excel保存工作簿。

 Sub Mac2() Dim varResult As Variant Dim ActBook As Workbook 'displays the save file dialog varResult = Application.GetSaveAsFilename(FileFilter:= _ "Excel Files (*.xlsx), *.xlsx", Title:="Save PO", _ InitialFileName:="\\showdog\service\Service_job_PO\") 'checks to make sure the user hasn't canceled the dialog If varResult <> False Then ActiveWorkbook.SaveAs Filename:=varResult, _ FileFormat:=xlWorkbookNormal Exit Sub End If End Sub 

使用GetSaveAsFilename只获取要保存的文件的path,而SaveAs方法实际上保存工作簿。

经过一些考虑,我可能会build议使用SaveCopyAs方法而不是简单的SaveAs。 顾名思义,这将使您的原始工作簿保持完整,并保存副本。 要做到这一点是一个相当简单的修改。

你会replace

 ActiveWorkbook.SaveAs Filename:=varResult, _ FileFormat:=xlWorkbookNormal 

 ActiveWorkbook.SaveCopyAs Filename:=varResult 

我要补充的最后一个考虑是,如果您将启用macros的工作簿保存为.xlsx(通过SaveAs或SaveCopyAs),那么您将丢失macros,无论是在原始工作簿中使用SaveAs还是在副本中保存如果您使用SaveCopyAs。 如果需要macros可用,我会考虑将该文件另存为.xlsm。

我有同样的问题,但更喜欢使用最短的代码:

  Application.Dialogs(xlDialogSaveAs).Show ("c:\my_folder\") 

这是标准的Excel保存对话框。

它有几个参数(没有命名),你可能需要EM:

  Dim strFilename As String: strFilename = "report1" Dim strFolder As String: strFolder = "C:\temp\" 'initial directory - NOTE: Only works if file has not yet been saved! Dim xlfFileFormat As XlFileFormat: xlfFileFormat = XlFileFormat.xlOpenXMLWorkbook 'or replace by other XlFileFormat Dim strPassword As String: 'strPassword = "password" 'The password with which to protect the file - if any Dim booBackup As Boolean: 'booBackup = True '(Whether to create a backup of the file.) Dim strWriteReservationPassword As String: 'strWriteReservationPassword = "password2" ' (The write-reservation password of the file.) Dim booReadOnlyRecommendation As Boolean: booReadOnlyRecommendation = False '(Whether to recommend to the user that the file be opened in read-only mode.) Dim booWorkbookSaved As Boolean ' true if file saved, false if dialog canceled If Len(strFolder) > 0 Then ChDir strFolder booWorkbookSaved = Application.Dialogs(xlDialogSaveAs).Show(Arg1:=strFilename, Arg2:=xlfFileFormat, Arg3:=strPassword, _ Arg4:=booBackup, Arg5:=strWriteReservationPassword, Arg6:=booReadOnlyRecommendation)