无法将CSV转换为Excel(XLSX)

时间:2017-07-03 13:38:23

标签: vba excel-vba excel

我正在使用将CSV转换为Excel(xlsx)的宏。问题是,尽管扩展更改,新转换的文件到excel保留了CSV文件的结构,我的意思是,不是按列分隔。

myFile = Dir(myPath & "*.csv")
Set wb = Workbooks.Open(myPath & myFile)
wb.SaveAs myPath & Replace(myFile, ".csv", ""), xlOpenXMLWorkbook
wb.Close False

有什么不对吗?

谢谢!

1 个答案:

答案 0 :(得分:0)

您的文本文件包含Ansi编码的其他一些字符。 那需要删除“=”,引用。这个分隔符是分号。 行分隔符是“;;;”三个分号(我猜)。

Sub openCsv()
    Dim Wb As Workbook
    Dim myPath As String, myFile As String
    Dim newFile As String
    Dim s As String
    Dim vR(), vSplit, vSub
    Dim n As Long, i As Long, j As Integer

    myPath = ThisWorkbook.Path & "\" 'your path
    myFile = "myTest.csv" 'your csv file
    newFile = Split(myFile, ".")(0) & ".xlsx"


    s = TransFromUtf_8(myPath & myFile)
    s = Replace(s, "=", "")
    s = Replace(s, Chr(34), "")

    vSplit = Split(s, ";;;")
    For i = 0 To UBound(vSplit)
        n = n + 1
        vSub = Split(vSplit(i), ";")
        ReDim Preserve vR(1 To 30, 1 To n)
        For j = 0 To UBound(vSub)
            vR(j + 1, n) = vSub(j)
        Next j
    Next i
    Set Wb = Workbooks.Add
    With Wb
        With .Sheets(1)
            .Cells.NumberFormatLocal = "@"
            .Range("a1").Resize(n, 30) = WorksheetFunction.Transpose(vR)
            .Columns.AutoFit

        End With
        .SaveAs myPath & newFile
        .Close (0)
    End With

End Sub
Function TransFromUtf_8(myFile As String)
    Dim objStream
    Set objStream = CreateObject("ADODB.Stream")
    With objStream
        .Charset = "utf-8"
        .Open
        .LoadFromFile myFile
        TransFromUtf_8 = .ReadText
        .Close
    End With
    Set objStream = Nothing

End Function