我正在尝试格式化Excel文件的内容,并通过对话框自动将其保存在具有指定名称的指定位置。我有下面的代码,但是在保存文件后,我遇到了文件格式的问题。这是Excel提示我的问题:
此代码允许我将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
答案 0 :(得分:3)
我假设你的开头是CSV或其他非excel格式(文本文件等......)
如果您将实际保存文件的行更改为
wks.SaveAs (fdlg.SelectedItems(1)) , FileFormat:=xlOpenXMLWorkbook
将迫使VBA将文件保存在"更正"格式。最好实际选择在对话框中选择的格式,但我认为除了文件扩展名外,它不会被返回。你可以检测到它,然后选择匹配的格式,但如果你总是保存为XLSX,那么你可以使用上面的方法。