将范围复制到电子邮件

时间:2015-02-08 13:37:30

标签: excel excel-vba vba

我正在尝试设置一个范围来将Excel中的数据复制到电子邮件中,但下面的代码行只会复制一列和一行。

有人能帮助我吗?

ActiveSheet.Unprotect

Sheets("sheet1").Range("D4:D12").SpecialCells(xlCellTypeVisible)

1 个答案:

答案 0 :(得分:0)

您有两个选择:

1)如果您没有使用Microsoft Outlook并使用手动粘贴选项:

Sub CopyData()

    Dim Table1 As Range
    Dim ws1 As Worksheet

    Set ws1 = Worksheets("sheet1")
    Set Table1 = ws1.Range("A1:D4")

    Table1.Copy

End Sub

显然,更改工作表名称和范围以满足您的需求,您需要在用于显示数据的电子邮件应用程序中选择粘贴。

2)如果你使用的是Microsoft Outlook,那么你可以使用与我的代码非常相似的东西:

(注意:您需要确保在运行宏之前运行Microsoft Outlook)

Sub CopyData()

    Dim Table1 As String
    Dim ws1 As Worksheet
    Dim OutApp As Object
    Dim OutMail As Object

    Set ws1 = Worksheets("sheet1")
    Table1 = ws1.Range("A1:D4").value

    Set OutApp = CreateObject("Outlook.Application")
    Set OutMail = OutApp.CreateItem(0)

    With OutMail
        .HTMLBody = Table1
        .Display
    End With

    Set OutMail = Nothing
    Set OutApp = Nothing

End Sub



Function RangetoHTML(rng As Range)

Dim FSO As Object
Dim ts As Object
Dim TempFile As String
Dim TempWB As Workbook

TempFile = Environ$("temp") & "\" & Format(Now, "dd-mm-yy h-mm-ss") & ".htm"

'Copy the range and create a new workbook to past the data in
rng.Copy
Set TempWB = Workbooks.Add(1)
With TempWB.Sheets(1)
    .Cells(1).PasteSpecial Paste:=8
    .Cells(1).PasteSpecial xlPasteValues
    .Cells(1).PasteSpecial xlPasteFormats
    .Cells(1).Select
    Application.CutCopyMode = False
    On Error Resume Next
    .DrawingObjects.Visible = True
    .DrawingObjects.Delete
    On Error GoTo 0
End With

'Publish the sheet to a htm file
With TempWB.PublishObjects.Add( _
     SourceType:=xlSourceRange, _
     Filename:=TempFile, _
     Sheet:=TempWB.Sheets(1).Name, _
     Source:=TempWB.Sheets(1).UsedRange.Address, _
     HtmlType:=xlHtmlStatic)
    .Publish (True)
End With

'Read all data from the htm file into RangetoHTML
Set FSO = CreateObject("Scripting.FileSystemObject")
Set ts = FSO.GetFile(TempFile).OpenAsTextStream(1, -2)
RangetoHTML = ts.ReadAll
ts.Close
RangetoHTML = Replace(RangetoHTML, "align=center x:publishsource=", _
                      "align=left x:publishsource=")

'Close TempWB
TempWB.Close savechanges:=False

'Delete the htm file we used in this function
Kill TempFile

Set ts = Nothing
Set FSO = Nothing
Set TempWB = Nothing

End Function