【VBA】Count the Lines in File

You can count the Lines

in a File!

PR

VBA Code

For example, count following “text file“:

hogehoge1
hogehoge2
hogehoge3
hogehoge4
hogehoge5
5 lines.
text file
Option Explicit

Sub sampleProc()

    Dim fso As Object
    Dim fileName As String
    Dim lineCount As Long
    
    'Set "file path"
    fileName = "C:\Users\user\Desktop\hogehoge.txt"
    
    Set fso = CreateObject("Scripting.FileSystemObject")
    
    'Count the Lines in a File
    lineCount = fso.OpenTextFile(fileName:=fileName, iomode:=8).Line
    
    MsgBox lineCount & " Lines."
    
    Set fso = Nothing
    
End Sub

Set “file path“(Line 10).

Count “the Lines in a File“(Line 15).
*Use “OpenTextFile method” of “FileSystemObject”, return “TextStream Object”.
*Use “Line property” of “TextStream Object”.

*Set “iomode” to “8”.

If the file have opened, occurs the error.

Error Message.
Error Message.

You can count not only in “txt file”, but also in “csv file”.

PR

Result

You counted the Lines in a File!

result
PR

FYI

For more information about following, see the following official online manual:

●“OpenTextFile method” of “FileSystemObject”


●“Line property” of “TextStream Object”

タイトルとURLをコピーしました