簡體   English   中英

用HTMLbody替換文本(從Excel VBA創建電子郵件)

[英]Substitute text in HTMLbody (Creating email from Excel VBA)

我具有以下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

@Brax回答說, Replace是前往此處的正確方法。


對於希望了解此錯誤原因的任何人。

僅為了說明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

您可以使用Replace

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM