-1
我试图格式化Excel文件的内容,并通过对话框自动将其保存在指定位置并指定名称。我有下面的代码,但在保存文件后遇到文件格式问题。这是问题的是Excel提示我:Excel VBA:使用VBA保存时的文件格式错误
此代码可以让我格式化我的Excel文件我需要的格式,然后自动显示,我想将它保存位置和文件名。此代码使我可以成功保存excel文件。但是,当我尝试打开它时,它告诉我文件已损坏,或扩展名错误。
有谁知道我为什么遇到这个错误?谢谢!
代码:
Option Explicit
Sub externalRatingChangeFile()
'Declare the data type of the variables
Dim wks As Worksheet
Dim lastCol As Integer
Dim lastRow As Long
Dim iCol As Integer
Dim iRow As Long
Dim sFilename As String
Dim fdlg As FileDialog
Dim xlsxFileFormat As XlFileFormat
'Set wks to the current active worksheet
Set wks = ActiveWorkbook.ActiveSheet
Set fdlg = Application.FileDialog(msoFileDialogFilePicker)
'Set the location to save the file to a variable
sFilename = "H:\Testing File\Rating Change - " + Format(Date, "YYYYMMDD")
'xlsxFileFormat = XlFileFormat.xlOpenXMLWorkbook
'Within the current active worksheet, identify the last interested row and column of data
'Any values such as 'a', '1' or '%' are considered as values. Spaces (Spacebars) are not considered as values.
With wks
With .Cells(1, 1).CurrentRegion
lastCol = .Columns.Count
lastRow = .Rows.Count
End With
'Select the interested cells and insert borders around the interested fields
.UsedRange.Borders.LineStyle = xlContinuous
.UsedRange.Columns.AutoFit
End With
'Inserting a Row at the top to input Date
Range("A1").EntireRow.Insert
'Input today's Date
wks.Range("A1").Value = "Date: " + Format(Date, "DD MMMM YYYY")
'Save as .xlsx file in the specific location stated earlier
Set fdlg = Application.FileDialog(msoFileDialogSaveAs)
With fdlg
.InitialFileName = sFilename
.Show
'If there are errors in the code, set wks to nothing and end the process
On Error GoTo err_handler
wks.SaveAs (fdlg.SelectedItems(1))
End With
'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
我相信该文件将保存为文本文件,然后再将其保存在另一个位置。我在你的帮助下设法解决了这个问题。谢谢! – JJ2015