How to read every 20 lines from a text file using vbscript?

I have 180 lines in a text file and you want to read every 20 lines (1-20, 21-40 ...)

Here is my current code:

Const ForReading = 1 Set objFSO = CreateObject("Scripting.FileSystemObject") Set objTextFile = objFSO.OpenTextFile("C:\Bess_Automation\EditFiles\TSTVLD1.txt", ForReading) 'Reading the count of lines objTextFile.ReadAll strLinecount=objTextFile.Line msgbox strLinecount strnumoftimes=Round((strLinecount/20),0) msgbox strnumoftimes 
+5
source share
1 answer

This is how I approach the problem. This code sets the number of lines to be read at that time, first, then opens the file for reading and sets the array. Until we finish reading the file, we will add a line from it to myArray .

When we press the space bar 20 lines, we will report it and do everything we need with these 20 lines (in my case, I just recalled them to the screen, separated by semicolons).

Then we reset the array again and repeat until the entire file is read, and then output the final batch of lines (otherwise they will be ignored, since we only do something with batches of 20 as an example).

 Option Explicit Const LINES_TO_READ = 20 Dim iLines, iTotalLines Dim oFso : Set oFso = CreateObject("Scripting.FileSystemObject") Dim oFile : Set oFile = oFso.OpenTextFile("C:\temp\mytextfile.txt", 1) Dim myArray() ReDim myArray(0) iLines = 0 iTotalLines = 0 While Not oFile.AtEndOfStream myArray(UBound(myArray)) = oFile.ReadLine iLines = iLines + 1 ReDim Preserve myArray(UBound(myArray)+1) If iLines Mod LINES_TO_READ = 0 Then WScript.Echo iLines & " read now." ' do anything you like with the elements of myArray here before we reset it to empty WScript.Echo Join(myArray, ";") ' reset array to be totally empty again ReDim myArray(0) End If Wend WScript.Echo "Final Lines: " & Join(myArray, ";") WScript.Echo "Total lines in file: " & iLines 
+3
source

All Articles