テキストファイルは簡単に作成できる
VBAコードの中でテキストファイルを作成するのはコードさえ知っていれば比較的簡単です。
用途はあまり多くありませんが、例えばExcelやAccessのファイルを開いたときや閉じたときにログを残す機能を付けるのに役立ちます。
今回はテキストファイルを作成するコードを紹介します。
テキストファイルを作成する方法は2通り
テキストファイルを作成して、必要な内容を本文に記載する方法は私が調べた限り大きく2通りあります。
1つはFSO(FIleSystemObject)を使用する方法で、もう一つがMicrosoft Wordを使用する方法です。
①FSO(FIleSystemObject)を使用する方法
FSO.CreateTextFileというメソッドを用いて、テキストファイルを作成し、本文に文字を入力するVBAコードです。
Sub テキストで文字を書いて保存()
Dim FSO As Object, WSH As Object
Set FSO = CreateObject(“Scripting.FileSystemObject”)
Set WSH = CreateObject(“Wscript.Shell”)
Dim DesktopPath As String
DesktopPath = WSH.SpecialFolders(“Desktop”)
Dim 文章 As String
文章 = “aaaa” & vbCrLf & “bbbb”
With FSO.CreateTextFile(DesktopPath & “\リスト.txt”) ’リスト.txtというファイルを作成する
.WriteLine 文章 ’本文に変数「文章」の値を入力する
.Close
End With
Set FSO = Nothing
Set WSH = Nothing
End Sub
Dim FSO As Object, WSH As Object
Set FSO = CreateObject(“Scripting.FileSystemObject”)
Set WSH = CreateObject(“Wscript.Shell”)
Dim DesktopPath As String
DesktopPath = WSH.SpecialFolders(“Desktop”)
Dim 文章 As String
文章 = “aaaa” & vbCrLf & “bbbb”
With FSO.CreateTextFile(DesktopPath & “\リスト.txt”) ’リスト.txtというファイルを作成する
.WriteLine 文章 ’本文に変数「文章」の値を入力する
.Close
End With
Set FSO = Nothing
Set WSH = Nothing
End Sub
②Microsoft Wordを使用する方法
Microsoft Wordを起動して、ファイルをテキスト形式で保存するVBAコードです。
テキストファイルに保存するだけならWordが必要になりますし、時間もかかるのであまりメリットはないですが、他のファイル形式で保存することができるのが特徴です。
FileFormatの引数を0にすればWord文書、2にすればテキスト、17でPDFの形式で保存できます。
今回作成したVBAコードはWord以外のVBAで使用することを想定しているのでWordを起動するコードも含んでいます。
Sub テキストで文字を書いて保存2()
Dim FSO As Object, WSH As Object
Set FSO = CreateObject(“Scripting.FileSystemObject”)
Set WSH = CreateObject(“Wscript.Shell”)
Dim DesktopPath As String
DesktopPath = WSH.SpecialFolders(“Desktop”)
Dim 文章 As String
文章 = “aaaa” & vbCrLf & “bbbb”
Dim wdApp As Variant
Set wdApp = CreateObject(“Word.Application”)
With wdApp
.Visible = True
.Documents.Add
.Selection.typetext Text:=文章 ’本文に変数「文章」の値を入力する
.Documents(.Documents.Count).SaveAs2 Filename:=DesktopPath & “\リスト.txt”, FileFormat:=2 ’テキスト形式の保存
.Documents(.Documents.Count).Close
End With
wdApp.Quit
Set wdApp = Nothing
Set FSO = Nothing
Set WSH = Nothing
End Sub
Dim FSO As Object, WSH As Object
Set FSO = CreateObject(“Scripting.FileSystemObject”)
Set WSH = CreateObject(“Wscript.Shell”)
Dim DesktopPath As String
DesktopPath = WSH.SpecialFolders(“Desktop”)
Dim 文章 As String
文章 = “aaaa” & vbCrLf & “bbbb”
Dim wdApp As Variant
Set wdApp = CreateObject(“Word.Application”)
With wdApp
.Visible = True
.Documents.Add
.Selection.typetext Text:=文章 ’本文に変数「文章」の値を入力する
.Documents(.Documents.Count).SaveAs2 Filename:=DesktopPath & “\リスト.txt”, FileFormat:=2 ’テキスト形式の保存
.Documents(.Documents.Count).Close
End With
wdApp.Quit
Set wdApp = Nothing
Set FSO = Nothing
Set WSH = Nothing
End Sub
コメント