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

chhkpiq4  于 2023-03-24  发布在  其他
关注(0)|答案(3)|浏览(109)

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

末端子组件

bnl4lu3b

bnl4lu3b1#

在代码中添加了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
ccrfmcuu

ccrfmcuu2#

在我的脑海里:

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
guicsvcw

guicsvcw3#

'In O365 Excel the OpenTextFile statement should be CreateTextFile in order to
'create a new file.

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.CreateTextFile("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

相关问题