I'm trying to export some excel data to .csv in batches of 5 data rows plus 1 header.
My first file has 4 data rows which should be 5 plus the header as shown below
latitude,longitude,altitude(m),heading(deg),curvesize(m),rotationdir,gimbalmode,gimbalpitchangle,actiontype1,actionparam1
1,-0.5643113,100,0,0,0,2,-90,1,0
2,-0.56499336,100,180,0,0,2,-90,1,0
3,-0.56499336,100,180,0,0,2,-90,1,0
4,-0.56499336,100,180,0,0,2,-90,1,0
Whereas the remaining files have 5 data rows (which is correct)
latitude,longitude,altitude(m),heading(deg),curvesize(m),rotationdir,gimbalmode,gimbalpitchangle,actiontype1,actionparam1
5,-0.56499336,100,180,0,0,2,-90,1,0
6,-0.56815177,100,0,0,0,2,-90,1,0
7,-0.56815177,100,0,0,0,2,-90,1,0
8,-0.56815177,100,0,0,0,2,-90,1,0
9,-0.56815177,100,0,0,0,2,-90,1,0
Any ideas where I have gone wrong?
Sub Export()
Dim FileNum As Integer
Dim Last_Row As Long
Dim My_Range As Range
Dim TotalFileNum As Integer
Dim myStr As String
Dim MYFILE As String
Dim i As Integer
Dim j As Long
MYFILE = ThisWorkbook.Path & "\"
FileNum = FreeFile
Last_Row = Cells(Rows.Count, 1).End(xlUp).Row
Set My_Range = ActiveSheet.Range("A2:J" & Last_Row)
Open MYFILE & "Litch 0.csv" For Output As #FileNum
'Put out the headers
myStr = Cells(1, 1).Value
For i = 2 To 10
myStr = myStr & "," & Cells(1, i).Value
Next i
Print #FileNum, myStr
For j = 2 To Last_Row
If (j - 1) Mod 5 = 0 Then
Close #FileNum
Open MYFILE & "Litch " & ((j - 1) \ 5) & ".csv" For Output As #FileNum
'Put out the headers
myStr = Cells(1, 1).Value
For i = 2 To 10
myStr = myStr & "," & Cells(1, i).Value
Next i
Print #FileNum, myStr
TotalFileNum = (j \ 5) + 1
End If
'Put out the values
myStr = Cells(j, 1).Value
For i = 2 To 10
myStr = myStr & "," & Cells(j, i).Value
Next i
Print #FileNum, myStr
Next j
Close #FileNum
End Sub
Thanks in advance for the help
Maybe it's better to do everything in the loop
Option Explicit
Sub Export()
Dim FileNum As Integer
Dim Last_Row As Long
Dim My_Range As Range
Dim TotalFileNum As Integer
Dim myStr As String
Dim MYFILE As String
Dim i As Integer
Dim j As Long
MYFILE = ThisWorkbook.Path & "\"
Last_Row = Cells(Rows.Count, 1).End(xlUp).Row
Set My_Range = ActiveSheet.Range("A2:J" & Last_Row)
For j = 1 To Last_Row
If j = Last_Row Then
Close #FileNum
Exit For
End If
If (j - 1) Mod 5 = 0 Then
FileNum = FreeFile
Open MYFILE & "Litch " & ((j - 1) \ 5) & ".csv" For Output As #FileNum
'Put out the headers
myStr = Cells(1, 1).Value
For i = 2 To 10
myStr = myStr & "," & Cells(1, i).Value
Next i
Print #FileNum, myStr
TotalFileNum = (j \ 5) + 1
End If
'Put out the values
myStr = Cells(j + 1, 1).Value
For i = 2 To 10
myStr = myStr & "," & Cells(j + 1, i).Value
Next i
Print #FileNum, myStr
If j Mod 5 = 0 Then
Close #FileNum
End If
Next j
End Sub
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.