Skip to content

Instantly share code, notes, and snippets.

@jaw111
Created January 2, 2014 08:59
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save jaw111/8216600 to your computer and use it in GitHub Desktop.
Save jaw111/8216600 to your computer and use it in GitHub Desktop.
Simple VBA macro to split a text file (*.txt) into chunks where maximum number of lines for each chunk is entered by user. The output files get the same name as the source text file, but with _1, _2,... appended to the file name (example.txt => example_1.txt, example_2.txt etc.).
Sub split()
Dim fNameAndPath As Variant
Dim TextLine, fName
Dim fileCount, myCount, numberOfLines As Integer
Dim outputFile
myCount = 0
fileCount = 1
fNameAndPath = Application.GetOpenFilename(FileFilter:="Text files (*.txt), *.txt", Title:="Select File To Be Opened")
If fNameAndPath = False Then Exit Sub
'MsgBox fNameAndPath
fName = Right(fNameAndPath, Len(fNameAndPath) - InStrRev(fNameAndPath, "\"))
fName = Left(fName, InStr(fName, ".") - 1)
'MsgBox fName
numberOfLines = CInt(InputBox("Enter the number of lines per file", "Enter number of lines", "100"))
Open fNameAndPath For Input As #1 ' Open file.
Do While Not EOF(1) ' Loop until end of file.
outputFile = fName & "_" & fileCount & ".txt"
'MsgBox outputFile
Open outputFile For Output Shared As #2
Do While (myCount < numberOfLines And Not EOF(1))
Line Input #1, TextLine ' Read line into variable.
Print #2, TextLine ' write variable to output file.
myCount = myCount + 1
Loop
Close #2
fileCount = fileCount + 1
myCount = 0
Loop
Close #1 ' Close file.
End Sub
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment