vba使用分号分隔符复制csv文件

时间:2014-04-19 09:15:20

标签: excel vba csv delimiter

我正在使用宏将csv文件复制到新工作表中,这部分效果很好。 但是,我的csv文件使用分号作为分隔符,当我使用以下代码时,文本不会拆分成列:

Sub Bam()
    Dim FilesToOpen
    Dim wkbAll As Workbook
    Dim wkbTemp As Workbook
    Dim newSheet As Worksheet
    FilesToOpen = Application.GetOpenFilename _
    (FileFilter:="Text Files (*.csv), *.csv", Title:="Text Files to Open")  
    Set wkbTemp = Workbooks.Open(Filename:=FilesToOpen)
    wkbTemp.Sheets(1).Cells.Copy
    Set newSheet = ThisWorkbook.Sheets.Add
    With newSheet
        .Name = wkbTemp.Name
        .PasteSpecial
    End With
    Application.CutCopyMode = False
    wkbTemp.Close
End Sub

我尝试使用以下命令将分号设置为分隔符:

With newSheet
    .Name = wkbTemp.Name
    .PasteSpecial
    .TextToColumns DataType:=xlDelimited, ConsecutiveDelimiter:=True, Semicolon:=True
End With

Set wkbTemp = Workbooks.Open(Filename:=FilesToOpen, Delimiter:=4)

但是,在第一种情况下,当我尝试使用我的宏时出现以下错误消息:

突出显示.TextToColumns

Compile error:
Method or data member not found.

在第二种情况下,没有任何反应,所有文本仍然出现在一列中。

有没有人有想法将分号设置为分隔符?

谢谢

2 个答案:

答案 0 :(得分:0)

我首先将数据放入 A 列中,然后解析数据:

Sub Bam()
    Dim FilesToOpen, v As Variant
    Dim wkbAll As Workbook
    Dim wkbTemp As Workbook
    Dim newSheet As Worksheet, N As Long, J As Long
    FilesToOpen = Application.GetOpenFilename _
    (FileFilter:="Text Files (*.csv), *.csv", Title:="Text Files to Open")
    Close #1
    Open FilesToOpen For Input As #1
    J = 1
    Do While Not EOF(1)
            Line Input #1, TextLine
            Cells(J, 1) = TextLine
            J = J + 1
    Loop
    Close #1

    N = Cells(Rows.Count, "A").End(xlUp).Row
    For J = 1 To N
        v = Cells(J, 1).Value
        If InStr(v, ";") > 0 Then
            ary = Split(v, ";")
            For i = LBound(ary) To UBound(ary)
                Cells(J, i + 1).Value = ary(i)
            Next i
        End If
    Next J
End Sub

答案 1 :(得分:0)

我喜欢你的方式,我会研究它。与此同时,我找到了办法!我将* .csv文件的扩展名修改为* .txt,并略微更改了代码:

Sub Bam()
    Dim FilesToOpen
    Dim wkbAll As Workbook
    Dim wkbTemp As Workbook
    Dim newSheet As Worksheet
    FilesToOpen = Application.GetOpenFilename(Title:="Text Files to Open")
        Set wkbTemp = Workbooks.Open(Filename:=FilesToOpen, Format:=4)
        wkbTemp.Sheets(1).Cells.Copy
        Set newSheet = ThisWorkbook.Sheets.Add
        With newSheet
            .Name = wkbTemp.Name
            .PasteSpecial
        End With
        Application.CutCopyMode = False
        wkbTemp.Close   
End Sub

这不完全是我想要的,因为我现在必须修改生成* .csv文件的脚本,但它有效!

感谢您的想法,我会认真研究它,也许我不必修改我的脚本。在所有情况下,非常感谢,我总是对新闻的工作方式感到好奇,并且总是希望改进我的代码! :)谢谢。