VBA – CreateTextFileでテキストファイルを作成する

Written by

Editorial Team

Reviewed by

Steve Rynearson

Translated by

masahiro yoshida

Last updated on 7月 3, 2022

このチュートリアルでは、VBAを使用してテキストファイルを作成する方法を説明します。

テキストファイルの作成

このレッスンでは、FileSystemObjectを使用します。これを使うには、Microsoft Scripting Runtimeへの参照が必要ですが、ここでは遅延バインディングを利用するため、事前設定は不要です。

テキストファイルを作成するには、以下のコードのようにCreateTextFileメソッドを使用します。

Sub FSOCreateTextFile()
    Dim FSO As Object
    Set FSO = CreateObject("Scripting.FileSystemObject")
    Dim TextFile As Object

    Set TextFile = FSO.CreateTextFile("C:\Test\TestFile.txt")

End Sub

CreateTextFileメソッドには、オプションの引数を渡すことができます。

  • 引数overwriteをtrueにすると、既に存在するファイルも上書きできます。
  • 引数unicodeをtrueにするとunicodeファイルが作成され、それ以外(または引数を省略した場合)はASCII(日本語完了ではShift-JIS)ファイルになります。

次の例では、既存のTestFile.txtがunicodeファイルで上書きされます。

Set TextFile = FSO.CreateTextFile("C:\Test\TestFile.txt", True, True)

テキストファイルへの書き込み

テキストファイルを作成した後、1行のコードでそのファイルにテキストを書き込むことができます。

TextFile.Write "コンテンツ"

Write、WriteLine、WriteBlankLinesの各メソッドを使ったテキストファイルへの書き込みについては、リンクをクリックしてください。

vba-free-addin

VBA Code Examples Add-in

Easily access all of the code examples found on our site.

Simply navigate to the menu, click, and the code will be inserted directly into your module. .xlam add-in.

(No installation required!)

Free Download

Return to VBA Code Examples