2017-10-19 101 views
0

我在將文件轉換爲其他格式時遇到問題。我有幾百個.csv格式的文件,需要轉換它們。我發現一個正在工作的sub(),但如果我首先打開文件然後手動保存,則格式看起來會有所不同。它來自哪裏?將.csv保存爲.xlsx

下面是宏我不打開文件使用:

Sub csv_to_xlsx() 
Dim CSVfolder As String, _ 
    XlsFolder As String, _ 
    fname As String, _ 
    wBook As Workbook 

CSVfolder = "C:\Users\ja\Desktop\CSV\" 
XlsFolder = "C:\Users\ja\Desktop\XLSX\" 

fname = Dir(CSVfolder & "*.csv") 

Do While fname <> "" 
    Set wBook = Workbooks.Open(CSVfolder & fname, Format:=6, Delimiter:=",") 
    wBook.SaveAs XlsFolder & Replace(fname, ".csv", ""), xlOpenXMLWorkbook 
    wBook.Close False 
    fname = Dir 
Loop 
End Sub 

和宏觀與打開文件:

Sub open_csv_save_xlsx() 

Dim sciezka As String, fileName As String, sheet As Worksheet, i As Integer, j As Integer 

Application.ScreenUpdating = False 
sciezka = ActiveWorkbook.Path & "\" 
fileName = Dir(sciezka & "*.csv") 
Do While fileName <> "" 
i = i + 1 
j = 2 
Cells(i, 1) = fileName 
fileName = Dir() 
Loop 
Application.ScreenUpdating = True 

Dim a As Integer, b As Integer, arkusz As String, XlsFolder As String, wBook As Workbook 
XlsFolder = "C:\Users\ja\Desktop\XLSX\" 
a = WorksheetFunction.CountA(Range("A:A")) 
b = 1 
For i = 1 To a - 1 
arkusz = Range("A" & b).value 
Range("C" & b).value = b 
b = b + 1 
Workbooks.Open (sciezka & arkusz) 
Set wBook = ActiveWorkbook 
wBook.SaveAs XlsFolder & Replace(sciezka & arkusz, ".csv", ""), xlOpenXMLWorkbook 
ActiveWorkbook.Close True 
Next i 

End Sub 

第一部分是使工作表的文件列表,並在線路wBook.SaveAs XlsFolder & Replace(sciezka & arkusz, ".csv", ""), xlOpenXMLWorkbook粉碎和我不知道原因。發生錯誤1004。

任何人有任何其他方式來轉換這個文件?爲什麼格式不同呢?

+0

這兩個代碼塊都會打開工作簿,而第一個代碼塊不會生成文件列表。首先嚐試單步執行代碼,以瞭解其實際執行的內容。 –

+0

@MacroMan是的,你是對的,有功能。打開第一個宏。我不理解的是手動保存和使用SUB()之間的區別。你有什麼想法嗎? – RafMil

回答

0

它看起來像你指定一個目錄兩次,在XlsFolderscienka

修改您的代碼這應該揭示問題:

MsgBox XlsFolder & Replace(sciezka & arkusz, ".csv", "") 
wBook.SaveAs XlsFolder & Replace(sciezka & arkusz, ".csv", ""), xlOpenXMLWorkbook 

我想你需要刪除scienka &

+0

是的!完美搭配。它解決了1004錯誤的問題,但最終的效果仍然不符合預期。問題在於我不瞭解手動保存和使用SUB()之間的區別。你有什麼想法嗎?也許我應該使用其他文件格式,然後xlOpenXMLWorkbook?我想在使用宏後的工作簿看起來像我手動保存它。 – RafMil

+0

您是否嘗試將擴展名添加到它,即「替換(arkusz,」.csv「,」.xlsx「)? –

+0

沒有幫助。我陷入了這個問題。 – RafMil