VBA Excel: .txt ファイルの内容を文字列型変数に割り当てる方法は?

VBA Excel: .txt ファイルの内容を文字列型変数に割り当てる方法は?

入力したパラメータに従って電子メールを送信する Excel の小さなサブを作成しました。

Sub Mail_LSP(mailsubject As String, consignee As String, coalcopy As String, mailbody As String)

Dim mlook As Outlook.MailItem

Set mlook = Outlook.Application.CreateItem(olMailItem)
mySubject = mailsubject
mlook.To = consignee
mlook.CC = coalcopy
mlook.Subject = mailsubject
mlook.Body = mailbody
mlook.Send

End Sub

mailbody パラメータを改善したいのですが、.txt ファイルの内容を変数に割り当てて、この変数をプロシージャのパラメータとして使用する方法はありますか?

答え1

試すFileSystemObject

Private Sub CommandButton1_Click()
Set fso = CreateObject("Scripting.FileSystemObject")
Path = Range("E3")
Set filestream = fso.OpenTextFile(Path, 1)
contents = filestream.ReadAll()
Range("F4") = contents
End Sub

答え2

次のような方法を見つけました:Open mailbody For Input As #1そしてLine Input #1

Sub Mail_LSP(mailsubject As String, consignee As String, coalcopy As String, mailbody As String)

Dim mlook As Outlook.MailItem
Dim linecontent As String
Dim mailcontent As String

Open mailbody For Input As #1

Do Until EOF(1)
    Line Input #1, linecontent
    mailcontent = mailcontent & vbNewLine & linecontent & vbNewLine
Loop

Close #1

Set mlook = Outlook.Application.CreateItem(olMailItem)
mySubject = mailsubject
mlook.To = consignee
mlook.CC = coalcopy
mlook.Subject = mailsubject
mlook.Body = mailcontent
mlook.Send

End Sub

関連情報