打开TAB分隔的CSV并另存为TAB分隔符

时间:2017-05-28 02:04:03

标签: excel vba csv

所以,我有CSV文件是Tab Delimited。 我有一个宏来更改文件的内容,然后使用代码保存它:

wb.Close SaveChanges:=True

问题是,它会以CSV逗号分隔保存。

当另一个例程打开文件时,它会搞砸。

我环顾四周,并没有找到一种方法将文件保存为Excel中的TAB分隔CSV。

有人能帮助我吗?以下是完整代码:

    Sub routine()


Dim wb As Workbook
Dim Path As String 'Caminho
Dim File As String 'Arquivo da pasta
Dim Folder As FileDialog 'Pasta de origem
Dim answer As Integer

'-------------------------------------------------------------------------------'




answer = MsgBox("This macro will ask you to select a folder and change all the files from that folder. This action is not reversible, so make a backup before proceeding.", vbYesNo + vbInformation, "Confirm Action")

If answer = vbYes Then

    Set Folder = Application.FileDialog(msoFileDialogFolderPicker)

    With Folder
    .Title = "Select Folder with CSV Files"
    .AllowMultiSelect = False
        If .Show <> -1 Then GoTo NextCode
        Path = .SelectedItems(1) & "\"
    End With

    'Caso o usuário cancele
NextCode:
    Path = Path
    If Path = "" Then GoTo Resetar
    File = Dir(Path & "*.csv*")



    Do While File <> ""
    Set wb = Workbooks.Open(Filename:=Path & File)


    Columns("A:A").Select
        Selection.TextToColumns Destination:=Range("A1"), DataType:=xlDelimited, _
        TextQualifier:=xlDoubleQuote, ConsecutiveDelimiter:=False, Tab:=True, _
        Semicolon:=False, Comma:=False, Space:=False, Other:=False, TrailingMinusNumbers:= _
        True


    Range("N:N, M:M, L:L, K:K, J:J, H:H, G:G, F:F, D:D, C:C ").EntireColumn.Delete
    Range("A2").EntireRow.Delete
    wb.sav
    wb.Close SaveChanges:=True



    DoEvents
    File = Dir
    Loop


    MsgBox "CSV Files From Folder Updated"


Else
    GoTo Resetar


Resetar:
MsgBox "User Cancelled Action"

End If

End Sub

1 个答案:

答案 0 :(得分:1)

因为该文件具有.csv而不是.txt扩展名。 The tab delimiter can be specified when opening

Set wb = Workbooks.Open(Filename:=Path & File, Format:=1)

Range("C:D, H:F, J:N").EntireColumn.Delete
Rows(2).EntireRow.Delete

Application.DisplayAlerts = False
wb.Sheets(1).SaveAs Filename:=Path & File, FileFormat:=xlTextWindows
wb.Close SaveChanges:=False
Application.DisplayAlerts = True