使用 VBScript 从 CSV 文件中删除列

Using VBScript to delete a column from CSV file

我需要使用 VBScript 从 CSV 文件中删除各种列。

要剔除的列是第101到第106列

我下面的代码没有删除任何列:

Const ForReading = 1, ForWriting = 2, ForAppending = 8
Dim fso, strLine, dataArray, clippedArray()

InputFile="C:\input.csv"
OutputFile="C:\input_n_1.csv"

Set fso = CreateObject("Scripting.FileSystemObject")

Set InFile = fso.OpenTextFile(InputFile, ForReading)
Set OutFile = fso.OpenTextFile(OutputFile, ForWriting, True)

Do While InFile.AtEndOfStream <> True

    strLine = InFile.ReadLine
    ReDim Preserve clippedArray(x)
    clippedArray(x) =  Split(strLine,";")

    intCount = 0
    newLine = ""

    For Each Element In clippedArray(x)    
        If intCount <> (101 OR 102 OR 103 OR 104 OR 105 OR 106) Then
           EndChar = "|"
           newLine = newLine & Element & EndChar
        End If
        intCount = intCount + 1 
    Next

    OutFile.WriteLine newLine

Loop

InFile.Close
OutFile.Close

WScript.Echo "Done"   

循环中的代码存在一些问题。例如,当尝试 ReDim 您的 clippedArray 数组时,没有为 x 指定任何值。也不需要 Preserve 数组中的内容,因为您要在其中放置新数据。

循环的内部可以简化并放入这样的函数中:

Function GetUpdatedLine(p_sLine)
    Dim arrColumns
    Dim sNewLine
    Dim sEndChar
    Dim iCounter
    
    ' Split line into columns
    arrColumns = Split(p_sLine, ";")

    ' Initialize variables
    sNewLine = ""
    sEndChar = "|"

    For iCounter = 1 To UBound(arrColumns) + 1
    
        Select Case iCounter
            
            Case 101, 102, 103, 104, 105, 106
                ' Skip these columns
                
            Case Else
                ' Add to new line
                If sNewLine <> "" Then sNewLine = sNewLine & sEndChar ' Add separator
                sNewLine = sNewLine & arrColumns(iCounter - 1) ' arrColumns is a zero-based array
        End Select
    
    Next

    GetUpdatedLine = sNewLine

End Function

您的循环现在可以更新为:

Do While InFile.AtEndOfStream <> True
    OutFile.WriteLine GetUpdatedLine(InFile.ReadLine)
Loop