在excel中导入csv文件后删除多个标头

时间:2016-06-14 08:51:55

标签: excel vba csv

我需要使用excel makro将数百个具有相同格式的csv文件组合到一个没有重复标题的文件中。 我可以使用以下代码选择要导入的文件(并导入它们):

Dim dateien, i, lastrow
lastrow = 1
dateien = Application.GetOpenFilename _
("csv-Dateien (*.csv), *.csv", MultiSelect:=True)

If IsArray(dateien) Then
    For i = 1 To UBound(dateien)
        Workbooks.Open dateien(i), local:=True
        With ThisWorkbook.Sheets(1)
            ActiveSheet.UsedRange.Copy Destination:=.Range("A" & lastrow)
            lastrow = .UsedRange.Rows.Count + 1
        End With
        ActiveWorkbook.Close False
    Next i
End If

但是,我并不知道如何删除重复的标题...

1 个答案:

答案 0 :(得分:1)

我会采用在FileSystemObject中打开每个文件的方法,读取其中的所有数据,然后在没有标题的情况下将其重新启动:

Dim dateien, i, lastrow
lastrow = 1
dateien = Application.GetOpenFilename _
("csv-Dateien (*.csv), *.csv", MultiSelect:=True)

dim oFso : Set oFso = CreateObject("Scripting.FileSystemObject")
Dim oSourceFile, oTargetFile
Set oTargetFile = oFso.CreateTextFile("pathtofilehere", True)
Dim sArray()

If IsArray(dateien) Then
    For i = 1 To UBound(dateien) ' Arrays in VBA index from zero, not 1 - you're skipping the first element in dateien
        ReDim sArray(0)
        Set oSourceFile = oFso.OpenTextFile(dateien(i), 1) ' open for reading
        While Not oSourceFile.AtEndOfStream ' while there is data in the file
            sArray(Ubound(sArray)) = oSourceFile.ReadLine  ' add the line to an array
            ReDim Preserve sArray(UBound(sArray)+1) ' increase size of the array by 1
        Wend
        ' Now we have the whole file in an array
        For myLoop = 1 to UBound(sArray) ' Loop from 1 and we skip the header line in the file
            oTargetFile.WriteLine sArray(myLoop) ' write array values into file
        Next myLoop   ' repeat for each line in the array
    Next i    ' repeat for each file in dateien
End If