1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114
| Sub SplitTextFile(nblignes As Integer)
'Splits a text or csv file into smaller files
'with a user defined number (max) of lines or
'rows. The new files get the original file
'name + a number (1, 2, 3 etc.).
Dim sFile As String 'Name of the original file
Dim sText As String 'The file text
Dim lStep As Long 'Max number of lines in the new files
Dim vX, vY 'Variant arrays. vX = input, vY = output
Dim iFile As Integer 'File number from Windows
Dim lCount As Long 'Counter
Dim lIncr As Long 'Number for file name
Dim lMax As Long 'Upper limit for loop
Dim lNb As Long 'Counter
Dim lSoFar As Long 'How far did we get?
On Error GoTo ErrorHandle
'Select a file
sFile = Application.GetOpenFilename()
'If the user cancelled
If sFile = "False" Then Exit Sub
'Ask the user for max number of lines per file. E.g. 65536
lStep = nblignes
'Our arrays have zero as LBound, so we subtract 1
lStep = lStep - 1
'Read the file text to sText
sText = _
CreateObject("Scripting.FileSystemObject").OpenTextFile(sFile).ReadAll
'Put the text into the array vX. CrLf chars (new
'line) will add a new row to the array.
vX = Split(sText, vbCrLf)
'If Carriage returnlinefeed doesn't work try only linefeed :
'vX = Split(sText, vbLf)
'Free memory
sText = ""
'Now we start a loop that will run until all
'rows in the array have been read and saved
'into new files. The variable lSoFar keeps
'track of how far we are in vX.
Do While lSoFar < UBound(vX)
'If the number of rows minus lSoFar is
'bigger than max number of rows, the
'array vY is dimensioned to max number
'of rows.
If UBound(vX) - lSoFar >= lStep Then
ReDim vY(lStep)
'lMax is set = last rownumber to be
'copied to vY.
lMax = lStep + lSoFar
Else
'Else we dimension vY to the number of
'rows left.
ReDim vY(UBound(vX) - lSoFar)
'Last row to copy is last row in vX
lMax = UBound(vX)
End If
lNb = 0
'Now we copy the rows from vX to vY
For lCount = lSoFar To lMax
vY(lNb) = vX(lCount)
lNb = lNb + 1
Next
'lSoFar keeps track of how far we got in vX
lSoFar = lCount
'Get a free file number
iFile = FreeFile
'Increment the number for the new file name
lIncr = lIncr + 1
'Save vY as a text file (.txt). It could also be a csv-file,
'but then you need to replace txt with csv.
Open sFile & "-" & lIncr & ".csv" For Output As #iFile
'The Join function makes a text
'string from the array elements.
Print #iFile, Join$(vY, vbCrLf)
Close #iFile
Loop
Erase vX
Erase vY
Exit Sub
ErrorHandle:
MsgBox Err.Description & " Procedure SplitTextFile"
End Sub
Sub TestSplitCSV()
SplitTextFile (440)
End Sub |