如何使用VBA更改csv文件中列的顺序?

时间:2012-12-02 21:22:28

标签: excel vba

我有3个csv文件,我必须合并,但在此之前,我必须准备然后有相同的列顺序。一切正常,除了我到目前为止无法弄清楚如何改变输出文件中列的顺序。我可以选择我想要的列和其他跳过的但是如果我想换掉一些怎么办?我认为在fieldinfo数组中按顺序排列可以解决这个问题但不行。我想用6交换8。

    Application.ScreenUpdating = False
    Workbooks.OpenText Filename:=Filenamenew, Origin:=xlWindows, StartRow _
    :=2, DataType:=xlDelimited, TextQualifier:=xlDoubleQuote, _
    ConsecutiveDelimiter:=False, Tab:=False, Semicolon:=False, Comma:=True, _
    Space:=False, Other:=False, FieldInfo:=Array(Array(1, 3), Array(2, 9), Array(3, 1), Array(4, 9), Array(5, 9), Array(8, 1), Array(7, 9), Array(6, 1))

    Set Wb = ActiveWorkbook
    Application.DisplayAlerts = False
    Wb.SaveAs Filename:=LBname, FileFormat:=FileFormatNum, _
    ReadOnlyRecommended:=False, _
    CreateBackup:=False
    Application.DisplayAlerts = True

    Wb.Close savechanges:=False

感谢

1 个答案:

答案 0 :(得分:2)

最佳方法是更改​​创建需要更改的CSV文件的输出。我认为你无论出于什么原因都无法访问它,所以这将完成工作:

Sub swapColumns(first As Integer, second As Integer)
    Dim wb As Workbook
    Dim ws As Worksheet

    Set wb = Workbooks.Open("C:\root\test.csv")
    Set ws = wb.Sheets(1)
    If first > second Then
        Dim i As Integer
        i = first
        first = second
        second = i
    ElseIf first = second Then
        Exit Sub
    End If
    ws.Columns(second).Cut
    ws.Columns(first).Insert Shift:=xlToRight
    ws.Columns(first + 1).Cut
    ws.Columns(second + 1).Insert Shift:=xlToRight
End Sub

您可以使用swapColumns 6, 8

从现有代码中调用此Sub