将.csv保存为.xlsx

时间:2017-10-19 09:14:51

标签: excel vba excel-vba

我将文件转换为其他格式时遇到问题。我有几百个.csv格式的文件,需要转换它们。我找到了一个工作的sub()但是如果我先打开文件然后手动保存,格式看起来会有所不同。它来自哪里?

这是我在没有打开文件的情况下使用的宏:

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。

有没有其他方法可以转换这些文件?为什么格式化会出现差异?

1 个答案:

答案 0 :(得分:0)

您似乎在XlsFolderscienka中指定了两次目录。

修改您的代码应该揭示问题:

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

我想你需要删除scienka &