我在网上找到了这段代码,打开了一个另存为对话框的驱动器上的位置,让用户保存文件。当您点击"保存"该文件无法保存。我不知道我在这里做错了什么。帮助
以下是相关代码:
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
答案 0 :(得分:11)
您必须明确告知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
只获取要保存的文件的路径,而SaveAs
方法实际上保存了工作簿。
经过一些考虑,我建议使用SaveCopyAs方法而不是简单的SaveAs。顾名思义,这将使您的原始工作簿保持完整并保存副本。要做到这一点是一个相当简单的修改。
你会替换
ActiveWorkbook.SaveAs Filename:=varResult, _
FileFormat:=xlWorkbookNormal
使用
ActiveWorkbook.SaveCopyAs Filename:=varResult
我要补充的最后一个考虑因素是,如果您将启用宏的工作簿保存为.xlsx(通过SaveAs或SaveCopyAs),那么如果您使用SaveAs或者在原始工作簿中,您将丢失宏。如果使用SaveCopyAs,则保存的副本。如果你需要宏可用,我会考虑将文件保存为.xlsm。
答案 1 :(得分:2)
我有同样的问题,但更喜欢使用最短的代码:
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)