HTMLbody中的替换文本(从Excel VBA创建电子邮件)

时间:2017-10-24 16:22:02

标签: excel vba excel-vba email

我有以下VBA代码使用电子邮件模板正确创建电子邮件,但我正在尝试使用Substitute()功能更改电子邮件正文中的某些文本。我收到一个错误,不确定如何解决这个问题,任何帮助都会很棒!

  

运行时错误'1004':

     

无法获取WorksheetFunction类的Substitute属性

以下是尝试从我的模板创建电子邮件的代码...

Public Function GenerateEmail(fileName As String)

    Application.ScreenUpdating = False

    Dim OutApp As Object
    Dim OutMail As Object

    Set OutApp = CreateObject("Outlook.Application")
    Set OutMail = OutApp.CreateItemFromTemplate(fileName)

    With OutMail
        .HTMLbody = WorksheetFunction.Substitute(OutMail.HTMLbody, "%TESTNUM%", "98541")
        .Attachments.Add (Application.ActiveWorkbook.FullName)
        .Display
    End With

    On Error GoTo 0

    Set OutMail = Nothing
    Set OutApp = Nothing

    With Application
        .ScreenUpdating = True
        .EnableEvents = True
    End With

End Function

2 个答案:

答案 0 :(得分:2)

Replace是@Brax回答的正确方法。

  

对于任何想要了解此错误背后原因的人。

为了解释为什么1004发生了替换,你需要在使用WorksheetFunction时检查参数。

此问题是Excel单元格中允许的字符数。您只能在单元格中放置32767个字符。现在,当然,你的HTMLBody中有更多的字符,因此错误。

Sub Test()

    Dim validString     As String
    Dim inValidString   As String

    validString = "a" & Space(32766)
    inValidString = "b" & Space(32767)


    '/ Works as the string length is valid cell length : < =32767
    MsgBox WorksheetFunction.Substitute(validString, "a", "b")

    '/ Fails as the string length is invalid in terms of cell length : >32767
    MsgBox WorksheetFunction.Substitute(inValidString, "a", "b")

End Sub

答案 1 :(得分:1)

您可以使用Replace

.HTMLbody = Replace(OutMail.HTMLbody, "%TESTNUM%", "98541")