OpenTextFileメソッド

指定されたファイルを開き、ファイルの読取り、ファイルへの書込みまたはファイルへの追加に使用できるTextStreamオブジェクトを戻します。

構文

object.OpenTextFile(filename[, iomode[, create]])

引数:

  • Object: 必須。オブジェクトは、常にFileSystemObjectの名前です。
  • Filename: 必須。開くファイルを識別する文字列式。
  • Iomode: オプション。ForReading、ForWritingまたはForAppendingの3つの定数のいずれかを指定できます。
  • Create: オプション。指定されたファイル名が存在しない場合に、新しいファイルを作成できるかどうかを示すブール値。値は、新しいファイルを作成する場合はTrue、作成しない場合はFalseです。省略すると、新しいファイルは作成されません。
  • Format: オプション。開いたファイルのフォーマットを示します。

    注:

    Format引数は休止状態であり、VBスクリプト構文と似せるために保持されています。効果はありません。作成されるファイルはすべてUnicodeフォーマットのみです。

設定

iomode引数には、次のいずれかの設定を指定できます:

表11-34 IOMode引数の設定

定数 説明
ForReading 1 読取り専用でファイルを開きます。このファイルへの書込みはできません。
ForWriting 2 書込み用にファイルを開きます。
ForWriting 8 ファイルを開き、ファイルの末尾に書き込みます。

備考

次のコードは、OpenTextFileメソッドの使用方法を示しています。

注:

  • 新しいファイルが作成される場合は、Unicodeフォーマットで作成されます。

  • ファイルが存在しない場合、コードはReadModeでエラーをスローします。

例1:

Sub OpenFileForReading()
    Const ForReading = 1
    Dim fso, tso
    Set fso = CreateObject("Scripting.FileSystemObject")
    Set tso = fso.OpenTextFile("C:\example1.txt", ForReading)    
    tso.Close               ' Close the file.

    Set tso = Nothing
    Set fso = Nothing
End Sub

Call OpenFileForReading
'If C:\example1.txt is not present then code will throw an error. 

例2:

Sub OpenFileForWriting()
    Const ForWriting = 2
    Dim fso, file
    Set fso = CreateObject("Scripting.FileSystemObject")
    Set file = fso.OpenTextFile("C:\example2.txt", ForWriting, True)
    
    file.WriteLine("This is written to the file.")   ' Writes text to the file.
    file.Close               ' Close the file.

    Set file = Nothing
    Set fso = Nothing
End Sub

Call OpenFileForWriting
'Creates C:\example2.txt and writes a line "This is written to the file."

例3:

Sub OpenFileForAppending()
    Const ForAppending = 8
    Dim fso, file
    Set fso = CreateObject("Scripting.FileSystemObject")
    Set file = fso.OpenTextFile("C:\example2.txt", ForAppending, True)
    
    file.WriteLine("This line is appended.")   ' Appends text to the file.
    file.Close               ' Close the file.

    Set file = Nothing
    Set fso = Nothing
End Sub

Call OpenFileForAppending
'Creates C:\example2.txt and writes a line "This line is appended.". If file already exists it appends this line.

例4:

Sub OpenFileWithCreateOption()
    Const ForWriting = 2
    Dim fso, file
    Set fso = CreateObject("Scripting.FileSystemObject")
    Set file = fso.OpenTextFile("C:\example2.txt", ForWriting, True)   ' Creates the file if it doesn't exist.

    file.WriteLine("New File created and text written.")   ' Writes text to the file.
    file.Close               ' Close the file.
 
    Set file = Nothing
    Set fso = Nothing
End Sub

Call OpenFileWithCreateOption
'Overwrites C:\example2.txt and writes a line "New File created and text written.". If file does not exists then it creates it.