【问题标题】:Using VBScript to delete a column from CSV file使用 VBScript 从 CSV 文件中删除一列
【发布时间】:2021-02-17 16:46:43
【问题描述】:

我需要使用 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"   

【问题讨论】:

    标签: csv vbscript multiple-columns


    【解决方案1】:

    循环中的代码存在一些问题。例如,在尝试 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
    

    【讨论】:

      猜你喜欢
      • 2015-09-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-01-16
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多