将带有标题的大型CSV文件拆分为多个CSV文件,每个第n行都有一个标题

时间:2012-09-28 14:41:39

标签: excel csv excel-vba vbscript vba

我有一个大型CSV文件,我想将其拆分为多个CSV文件。我已经尝试了很多VBS脚本,但我似乎无法得到它。

此脚本执行我想要的一些操作,但不将它们保存为CSV文件:

Sub Split()
Dim rLastCell As Range
Dim rCells As Range
Dim strName As String
Dim lLoop As Long, lCopy As Long
Dim wbNew As Workbook

With ThisWorkbook.Sheets(1)
    Set rLastCell = .Cells.Find(What:="*", After:=[A1], SearchDirection:=xlPrevious)

    For lLoop = 1 To rLastCell.Row Step 35
        lCopy = lCopy + 1
        Set wbNew = Workbooks.Add
        .Range(.Cells(lLoop, 1), .Cells(lLoop + 35, .Columns.Count)).EntireRow.Copy _
        Destination:=wbNew.Sheets(1).Range("A1")
        wbNew.Close SaveChanges:=True, Filename:="Inventory_" & lLoop + 34
    Next lLoop
End With

End Sub

2 个答案:

答案 0 :(得分:3)

在代码中添加了saveas行以指定文件格式,您应该全部设置

Sub Split()
Dim rLastCell As range
Dim rCells As range
Dim strName As String
Dim lLoop As Long, lCopy As Long
Dim wbNew As Workbook

With ThisWorkbook.Sheets(1)
    Set rLastCell = .Cells.Find(What:="*", After:=[A1], SearchDirection:=xlPrevious)

    For lLoop = 2 To rLastCell.Row Step 35
        lCopy = lCopy + 1
        Set wbNew = Workbooks.Add
        .Cells(1, 1).EntireRow.Copy _
        Destination:=wbNew.Sheets(1).range("A1")
        .range(.Cells(lLoop, 1), .Cells(lLoop + 35, .Columns.Count)).EntireRow.Copy _
        Destination:=wbNew.Sheets(1).range("A2")
        wbNew.SaveAs FileName:="Inventory_" & format(lLoop + 34,"0000") & ".csv", FileFormat:=xlCSV, Local:=True
        wbNew.Close SaveChanges:=False
    Next lLoop
End With

End Sub

答案 1 :(得分:2)

脱离我的头顶:

Const ForReading = 1
Const ForWriting = 2

Set fso = CreateObject("Scripting.FileSystemObject")

maxRows = 35
i = 0
n = 0

Set out = Nothing
Set csv = fso.OpenTextFile("C:\PATH\TO\your.csv", ForReading)
header = csv.ReadLine

Do Until csv.AtEndOfStream
  If i = 0 Then
    If Not out Is Nothing Then out.Close
    Set out = fso.OpenTextFile("out_" & Right("00" & n, 2) & ".csv", ForWriting)
    out.WriteLine(header)
    n = n + 1
  End If
  out.WriteLine(csv.ReadLine)
  i = (i + 1) Mod maxRows
Loop

csv.Close    
If Not out Is Nothing Then out.Close