4

我有一个大的 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

结束子

4

2 回答 2

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
于 2012-09-28T15:58:43.943 回答
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
于 2012-09-28T15:02:20.230 回答