我正在尝试以.xlsx文件格式自动将.xls文件保存在硬编码位置。我希望SaveAs对话框显示硬编码位置,以及在"文件名中编码的文件名:"场。这样我只需单击“保存”按钮即可。
然而,当我想将文件保存在H盘中时,SaveAs对话框总是显示C盘。
以下是我的代码:
Option Explicit
Sub externalRatingChangeFile()
'Declare the data type of the variables
Dim wks As Worksheet
Dim sFilename As String
'Set wks to the current active worksheet
Set wks = ActiveWorkbook.ActiveSheet
'Set the location to save the file to a variable
sFilename = "H:\testing file"
'Save as .xlsx file in the specific location stated earlier
'If there are errors in the code, set wks to nothing and end the process
On Error GoTo err_handler
ChDrive sFilename
ChDir sFilename
Application.Dialogs(xlDialogSaveAs).Show (sFilename & "\TestingFile - " & Format(Date, "YYYYMMDD") & ".xlsx")
'System to/not display alerts to notify Users that they are replacing an existing file.
Application.DisplayAlerts = True
err_handler:
'Set Wks to its default value
Set wks = Nothing
End Sub
答案 0 :(得分:3)
不是显示“另存为”对话框,而是直接保存到文件夹。
Application.DisplayAlerts = False
wks.SaveAs (sFilename + "\TestingFile - " + Format(Date, "YYYYMMDD") + ".xlsx")
Application.DisplayAlerts = True
或
Application.DisplayAlerts = False
wks.SaveCopyAs (sFilename + "\TestingFile - " + Format(Date, "YYYYMMDD") + ".xlsx")
Application.DisplayAlerts = True
最后,您可以创建自己的对话框,以确保保存在正确的位置:
'Result = 2 is Cancel
'Result = 1 is Ok
result = MsgBox("Would You Like To Save in the Following Location: " + "H:\Test File....", vbOKCancel, "Save As")
答案 1 :(得分:2)
虽然我更喜欢Application.GetSaveAsFilename method(请参阅this),但在xlDialogSaveAs上设置初始文件夹应该没问题,前提是原始工作簿以前没有保存过。
Sub externalRatingChangeFile()
Dim bSaved As Boolean
Dim xlsxFileFormat As XlFileFormat
'Declare the data type of the variables
Dim wks As Worksheet
Dim sFilename As String
'Set wks to the current active worksheet
Set wks = ActiveWorkbook.ActiveSheet
'Set the location to save the file to a variable
sFilename = "H:\testing file"
xlsxFileFormat = XlFileFormat.xlOpenXMLWorkbook
'Save as .xlsx file in the specific location stated earlier
On Error GoTo err_handler
bSaved = Application.Dialogs(xlDialogSaveAs).Show(Arg1:=sFilename & "\TestingFile - " & Format(Date, "YYYYMMDD"), _
arg2:=xlsxFileFormat)
'System to/not display alerts to notify Users that they are replacing an existing file.
Application.DisplayAlerts = True
err_handler:
'Set Wks to its default value
Set wks = Nothing
End Sub