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

相关内容