0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

VBAのテキストファイル入出力でのオブジェクト指向なやり方

Last updated at Posted at 2022-09-30

テキストファイル入力

かつての方式

Dim strFile As String
Dim strLine As String
Dim num = FreeFile
strFile = "d:\work\testfile.txt"

Open strFile For Input As #num
Do Until EOF(num)
    Line Input #num, strLine
    ....
Loop
Close #num

よりモダンな方式

Dim fso As Object
Dim rf As Object
Dim strFilePath as String
Dim strLine As String
strFilePath = "d:\work\testfile.txt"

Set fso = CreateObject("Scripting.FileSystemObject")
Set rf = fso.OpenTextFile(strFilePath, ForReading, False)
Do While rf.AtEndOfStream <> True
    strLine = rf.ReadLine
    ...
Loop
rf.Close
Set fso = Nothing

テキストファイル出力

かつての方式

Dim strFilePath as String
Dim strLine As String
Dim num = FreeFile
strFilePath = "d:\work\testfile.txt"
strLine = "Hello world!"

Open strFilePath For Append As #num
Print #num, strLine
Close #num

よりモダンな方式

Dim fso As Object
Dim af As Object
Dim strFilePath as String
Dim strLine As String
strFilePath = "d:\work\testfile.txt"
strLine = "Hello world!"

Set fso = CreateObject("Scripting.FileSystemObject")
Set af = fso.OpenTextFile(strFilePath, ForAppending, True)
af.Write strLine
af.Close
Set fso = Nothing
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?