Splitting files using Visual Basic Scripts

Do you occasionally need to split a file based on its content?

If yes – then this can be done quickly by using a Visual Basic Script and “Scripting.FileSystemObject”.

Lets take a closer look.

First you have to define your source file and destination file.

FileCount = 0
DestFileName = “C:\destination”&FileCount&”.txt”

Set objFileSystemObject = CreateObject(“Scripting.FileSystemObject”)
Set objSource = objFileSystemObject.OpenTextFile(“C:\sourcefile.txt”, ForReading)
Set objDestination = objFileSystemObject.CreateTextFile(DestFileName, True)

Next you have to run through the Source File and write it to destinations files.

‘File Separator Mark
NewFileContent = “–start”

‘Run through the file
Do Until objSource.AtEndOfStream
……‘Read a line
……strLine = objSource.ReadLine

……‘Check if a new file should be created
……If InStr(1, strLine, NewFileContent) > 0 Then
………..‘Close Previous File
………..objDestination.Close
………..Set objDestination = Nothing

………..‘Create New FileName
………..FileCount = FileCount + 1
………..DestFileName = “C:\destination”&FileCount&”.txt”

………..‘Create and Open New File
………..Set objDestination = objFileSystemObject.CreateTextFile(DestFileName, True)
……End If

……‘Write to the file
……objDestination.WriteLine (strLine)
Loop

And the finally end by closing the open files

objSource.Close
objDestination.Close

Set objSource = Nothing
Set objDestination = Nothing
Set objFileSystemObject = Nothing

In the above example a file looking like this

–start
my first file
–start
my second file
–start
my third file

would be split in to the files:

destination1.txt containing:
–start
my first file

destination2.txt containing:
–start
my second file

destination3.txt containing:
–start
my third file

Be the first to comment

Leave a Reply

Your email address will not be published.


*


This site uses Akismet to reduce spam. Learn how your comment data is processed.