Search notes:

VBA: file class

The following is a class that basically encapsulates the call of freeFile() to determine the next available file number to be used with open and close.

Methods

open_(path)
print_(txt) Writes text into the opened file.
printWithNL(txt) Writes text into opened file and ends it with a new line.
close_()

Source code

'
' vi: ft=basic
'

option explicit

private fileNumber as integer

public sub open_(name_ as string) ' {

    if fileNumber <> 0 then ' {
       msgBox("fileNumber already set, name_ = " & name_)
       exit sub
    end if ' }

    fileNumber = freeFile()
    open name_ for output as #fileNumber

end sub ' }

public sub print_(txt as string) ' {
    print# fileNumber, txt; ' Semicolon to prevent printing of new line
end sub ' }

public sub printWithNL(txt as string) ' {
    print# fileNumber, txt  ' No semicolon, print new line
end sub ' }

public sub close_ ' {

    close #fileNumber
    fileNumber = 0

end sub ' }

private sub class_initialize()
end sub

private sub class_terminate()
end sub
Github repository VBAModules, path: /Filesystem/file.cls

Test

option explicit

sub main() ' {

    dim file_foo as file
    dim file_bar as file
    dim file_baz as file

    set file_foo = new file
    set file_bar = new file
    set file_baz = new file

    file_foo.open_ environ("temp") & "\filetest.foo.txt"
    file_bar.open_ environ("temp") & "\filetest.bar.txt"
    file_baz.open_ environ("temp") & "\filetest.baz.txt"

    file_foo.print_      "This "
    file_foo.print_      "is "
    file_foo.print_      "the "
    file_foo.print_      "first "
    file_foo.printWithNL "line. "

    file_bar.printWithNL "This is the bar file."
    file_baz.printWithNL "This is the baz file."

    file_foo.printWithNL "Second line"
    file_bar.printWithNL "Second line"
    file_baz.printWithNL "Second line"

    file_foo.close_
    file_bar.close_
    file_baz.close_

end sub ' }
Github repository VBAModules, path: /_test/Filesystem/file.vb

TODO

Should print_() and printWithNL() be renamed to write_ and writeWithNL.
Should the file class be used by the dbgFileWriter class?

See also

VBA Module File [Common]

Index