2016-04-19 227 views
-1

我試圖格式化Excel文件的內容,並通過對話框自動將其保存在指定位置並指定名稱。我有下面的代碼,但在保存文件後遇到文件格式問題。這是問題的是Excel提示我:Excel VBA:使用VBA保存時的文件格式錯誤

Error received

此代碼可以讓我格式化我的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 

回答

3

我假設你已經開始用CSV或其他非Excel格式(文本文件等)

如果改變了實際上的文件保存到

wks.SaveAs (fdlg.SelectedItems(1)) , FileFormat:=xlOpenXMLWorkbook 

這將強制VBA以「正確」格式保存文件。實際選擇對話框中選擇的格式會更好,但我不認爲它會在文件擴展名中返回。你可以檢測到,然後選擇匹配的格式,但如果你總是保存爲XLSX,那麼你可以使用上述方法。

+0

我相信該文件將保存爲文本文件,然後再將其保存在另一個位置。我在你的幫助下設法解決了這個問題。謝謝! – JJ2015