【问题标题】:Export Excel Table to HTML将 Excel 表格导出为 HTML
【发布时间】:2016-10-01 07:29:42
【问题描述】:

我正在运行一个代码,该代码从 Excel 工作表中获取数据,将其转换为 HTML 并作为电子邮件发送出去。以下是我使用的方法:

'replace html body'
 htmlString = Replace(htmlString, "#FIELD1#", ws.Range("D5").value)
 htmlString = Replace(htmlString, "#FIELD2#", ws.Range("C6").value)

现在我有一个完整的表格,我想将它复制粘贴到具有相同格式(边框、字体等)的 HTML 中

有人可以帮忙看看怎么做吗?

【问题讨论】:

标签: html excel vba


【解决方案1】:

答案在某种程度上取决于您的邮件客户端。 Outlook 与 VBA 紧密集成。如果您使用的是通用邮件客户端,您应该仍然能够完成任务,但可能会遇到问题。

如果您想从 Excel 中复制并在 Outlook 中粘贴为 HTML,则已回答:Copying values from excel to body of outlook email vb.net

如果您想使用通用电子邮件发送,请参阅下面的答案。我相信这适用于 HTML。 (如果您的邮件客户端对传递的 HTML 不满意,您可以将其转换为另存为文本文件。对于文本文件,您可以从开发人员功能区录制您自己的宏。只需开始录制并使用另存为另存为文本文件。)

下面有 3 个子/功能。我测试了 HTMLExport,这是我的代码。 SendEMail 来自 Chip Pearson 的站点,应该可以正常工作。 ExcelToHTMLToEMail我没有测试,它只是调用了前2个。

Sub ExcelToHTMLToEMail(BodyRngName as string,
        Subject As String, _
        FromAddress As String, _
        ToAddress As String, _
        SMTP_Server As String, _
        Optional Attachments As Variant = Empty)

    Dim BodyFileName As String

    BodyFileName = "C:\temp.htm"

    HTMLExport RngName, BodyFileName

    SendEMail Subject, _
        FromAddress, _
        ToAddress, _
        "", _
        SMTP_Server, _
        BodyFileName, _
        Optional Attachments
End Sub

Sub HTMLExport(RngName as string, _
    HtmlFileName as String, _
    Optional PageTitle as string = "")
    '
    ' HTMLExport Macro
    '
    Range(RngName).Select
    With ActiveWorkbook.PublishObjects.Add(xlSourceRange, HtmlFileName , _
        "Sheet1 (7)", RngName, xlHtmlStatic, , "MyPageTitle")
        .Publish (True)
        .AutoRepublish = False
    End With
End Sub

您可以从 Chip Pearson 找到从 Excel 发送电子邮件的代码:http://www.cpearson.com/Excel/EMail.aspx。这个网站包含一个巨大的 Excel VBA 代码库。 简介

添加从您的应用程序发送电子邮件的功能并不难。如果您只想发送只有主题但没有内容的工作簿,您可以使用 ThisWorkbook.SendMail。但是,如果您想在邮件正文中包含文本或包含附加文件作为附件,则需要一些 VBA 代码。该页面描述了一个名为 SendEmail 的函数,该函数将详细信息封装在一个很好的、对 VBA 友好的函数中。您可以在此处下载代码文件。

函数的定义是:

Function SendEMail(Subject As String, _
        FromAddress As String, _
        ToAddress As String, _
        MailBody As String, _
        SMTP_Server As String, _
        BodyFileName As String, _
        Optional Attachments As Variant) As Boolean

在哪里 主题是电子邮件的主题行。

FromAddress 是您的电子邮件地址。

ToAddress 是将电子邮件发送到的地址。您可以通过用分号分隔电子邮件地址来将消息发送给多个收件人。

MailBody 是作为邮件正文的文本。如果将此留空并且 BodyFileName 命名一个文本文件,则消息的正文将是 BodyFileName 命名的文件中的所有文本。如果 BodyFileName 和 MailBody 都为空,则发送的消息没有正文。

SMTP_Server 是您的外发邮件服务器的名称。

BodyFileName 是将用作消息正文的文本文件的名称。如果 MailBody 不为空,则忽略此参数并且不将文件用作正文。如果 MailBody 和 BodyFileName 都不为空,则将 MailBody 的内容用作正文,忽略 BodyFileName。

附件是要附加到邮件的单个文件名或文件名数组。如果附加其中一个文件时出错,将继续处理其余文件并发送电子邮件。

如果成功,该函数返回 True,如果发生错误,则返回 False。

代码需要引用 Microsoft CDO for Windows 2000 Library。此文件的典型文件位置是 C:\Windows\system32\cdosys.dll。该组件的 GUID 为 {CD000000-8B95-11D1-82DB-00C04FB1625D},Major = 1,Minor = 0。

分段

代码

代码如下所示。您可以在此处下载代码文件。

Function SendEMail(Subject As String, _
        FromAddress As String, _
        ToAddress As String, _
        MailBody As String, _
        SMTP_Server As String, _
        BodyFileName As String, _
        Optional Attachments As Variant = Empty) As Boolean
'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
' SendEmail Function
' By Chip Pearson, chip@cpearson.com www.cpearson.com 28-June-2012
'
' This function sends an email to the specified user.
' Parameters:
'   Subject:        The subject of the email.
'   FromAddress:    The sender's email address
'   ToAddress:      The recipient's email address or addresses.
'   MailBody:       The body of the email.
'   SMTP_Server:    The SMTP-Server name for outgoing mail.
'   BodyFileName:   A text file containing the body of the email.
'   Attachments     A single file name or an array of file names to
'                   attach to the message. The files must exist.
' Return Value:
'   True if successful.
'   False if failure.
'
' Subject may not be an empty string.
' FromAddress must be a valid email address.
' ToAddress must be a valid email address. To send to multiple recipients,
' use a semi-colon to separate the individual addresses. If there is a
' failure in one address, processing terminates and messages are not
' send to the rest of the recipients.
' If MailBody is vbNullString and BodyFileName is an existing text file, the content
' of the file named by BodyFileName is put into the body of the email. If
' BodyFileName does not exist, the function returns False. The content of
' the message body is created by a line-by-line import from BodyFileName.
' If MailBody is not vbNullString, then BodyFileName is ignored and the body
' is not created from the file.
' SMTP_Server must be a valid accessable SMTP server name.
' If both MailBody and BodyFileName are vbNullString, the mail message is
' sent with no body content.
' Attachments can be either a single file name as a String or an array of
' file names. If an attachment file does not exist, it is skipped but
' does not cause the procedure to terminate.
'
' If you want to send ThisWorkbook as an attachment to the message, use code
' like the following:
'    ThisWorkbook.Save
'    ThisWorkbook.ChangeFileAccess xlReadOnly
'    B = SendEmail( _
'        ... parameters ...
'        Attachments:=ThisWorkbook.FullName)
'    ThisWorkbook.ChangeFileAccess xlReadWrite
'
'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
' Required References:
' --------------------
'   Microsoft CDO for Windows 2000 Library
'       Typical File Location: C:\Windows\system32\cdosys.dll
'       GUID: {CD000000-8B95-11D1-82DB-00C04FB1625D}
'       Major: 1    Minor: 0
'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''

Dim MailMessage As CDO.Message
Dim N As Long
Dim FNum As Integer
Dim S As String
Dim Body As String
Dim Recips() As String
Dim Recip As String
Dim NRecip As Long

' ensure required parameters are present and valid.
If Len(Trim(Subject)) = 0 Then
    SendEMail = False
    Exit Function
End If

If Len(Trim(FromAddress)) = 0 Then
    SendEMail = False
    Exit Function
End If

If Len(Trim(SMTP_Server)) = 0 Then
    SendEMail = False
    Exit Function
End If

' Clean up the addresses
Recip = Replace(ToAddress, Space(1), vbNullString)
If Right(Recip, 1) = ";" Then
    Recip = Left(Recip, Len(Recip) - 1)
End If
Recips = Split(Recip, ";")


For NRecip = LBound(Recips) To UBound(Recips)
    On Error Resume Next
    ' Create a CDO Message object.
    Set MailMessage = CreateObject("CDO.Message")
    If Err.Number <> 0 Then
        SendEMail = False
        Exit Function
    End If
    Err.Clear
    On Error GoTo 0
    With MailMessage
        .Subject = Subject
        .From = FromAddress
        .To = Recips(NRecip)
        If MailBody <> vbNullString Then
            .TextBody = MailBody
        Else
            If BodyFileName <> vbNullString Then
                If Dir(BodyFileName, vbNormal) <> vbNullString Then
                    ' import the text of the body from file BodyFileName
                    FNum = FreeFile
                    S = vbNullString
                    Body = vbNullString
                    Open BodyFileName For Input Access Read As #FNum
                    Do Until EOF(FNum)
                        Line Input #FNum, S
                        Body = Body & vbNewLine & S
                    Loop
                    Close #FNum
                    .TextBody = Body
                Else
                    ' BodyFileName not found.
                    SendEMail = False
                    Exit Function
                End If
            End If ' MailBody and BodyFileName are both vbNullString.
        End If

        If IsArray(Attachments) = True Then
            ' attach all the files in the array.
            For N = LBound(Attachments) To UBound(Attachments)
                ' ensure the attachment file exists and attach it.
                If Attachments(N) <> vbNullString Then
                    If Dir(Attachments(N), vbNormal) <> vbNullString Then
                        .AddAttachment Attachments(N)
                    End If
                End If
            Next N
        Else
            ' ensure the file exists and if so, attach it to the message.
            If Attachments <> vbNullString Then
                If Dir(CStr(Attachments), vbNormal) <> vbNullString Then
                    .AddAttachment Attachments
                End If
            End If
        End If
        With .Configuration.Fields
            ' set up the SMTP configuration
            .Item("http://schemas.microsoft.com/cdo/configuration/sendusing") = 2
            .Item("http://schemas.microsoft.com/cdo/configuration/smtpserver") = SMTP_Server
            .Item("http://schemas.microsoft.com/cdo/configuration/smtpserverport") = 25
            .Update
        End With

        On Error Resume Next
        Err.Clear
        ' Send the message
        .Send
        If Err.Number = 0 Then
            SendEMail = True
        Else
            SendEMail = False
            Exit Function
        End If
    End With
Next NRecip
SendEMail = True
End Function
If you want to attach the workbook that contains the code, you need to make the file read-only when you send it and then change access back to read-write. For example,

ThisWorkbook.Save
ThisWorkbook.ChangeFileAccess xlReadOnly
B = SendEmail( _
    ... parameters ...
    Attachments:=ThisWorkbook.FullName)
ThisWorkbook.ChangeFileAccess xlReadWrite

【讨论】:

  • 感谢您的帮助!
猜你喜欢
  • 1970-01-01
  • 2019-10-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-05-15
  • 2018-06-24
  • 2023-03-21
  • 1970-01-01
相关资源
最近更新 更多