发送邮件Outlook时,VBA将Excel文件转换为文本

时间:2016-06-22 10:01:57

标签: excel vba excel-vba

如何在Outlook中发送邮件的同时转换我正在处理的activeworkbook? 这段代码有附件.xlsx文件,但我希望它在文本中,我该如何更改它? 谢谢

 'send mail code
                Set ol = New Outlook.Application
                Set olmail = ol.CreateItem(olMailItem)
                With olmail
                    .To = "test@outlook.com"
                    .Subject = objetText
                    .Body = "testing"
                    .Send

                .attachments.Add activeworkbook.fullname
                End With
            End sub

3 个答案:

答案 0 :(得分:2)

使用MS Office,您可以复制剪贴板中的Excel单元格区域,并将其粘贴到Outlook邮件正文中,如果该邮件正文是富文本格式并且您使用的是Word编辑器。在此过程中,单元格范围将转换为富文本表。

这也可以通过代码完成:

Sub emailer()

 Set oOlApp = CreateObject("Outlook.Application")

 olMailItem = 0
 Set oOlMItem = oOlApp.CreateItem(olMailItem)

 'get Excel cell range which shall be in the mail
 Set oWB = ActiveWorkbook
 Set oWS = ActiveWorkbook.Worksheets(1)
 Set oRange = oWS.Range("A1:C10")

 oRange.Copy ' Range is now in Clipboard

 With oOlMItem

  .Display

  .To = "email@email.com"
  .Subject = "Subject"

  Set oOlInsp = .GetInspector
  Set oWdDoc = oOlInsp.WordEditor ' get Word Document from the MailBody

  olFormatRichText = 3
  .BodyFormat = olFormatRichText ' change to RichTextFormat

  Set oWdRng = oWdDoc.Paragraphs(oWdDoc.Paragraphs.Count).Range
  oWdRng.InsertBefore "This is before the Excel table."
  oWdRng.InsertParagraphAfter
  oWdRng.InsertParagraphAfter

  Set oWdRng = oWdDoc.Paragraphs(oWdDoc.Paragraphs.Count).Range
  oWdRng.Paste ' paste Excel range from Clipboard

  oWdRng.InsertParagraphAfter

  Set oWdRng = oWdDoc.Paragraphs(oWdDoc.Paragraphs.Count).Range
  oWdRng.InsertBefore "This is after the Excel table."


 End With

 Application.CutCopyMode = False

End Sub

答案 1 :(得分:0)

您只能将1个工作表转换为文本,因此我假设这是您要完成的任务。将工作表复制到新工作簿(以便您可以继续使用当前工作簿作为xlsm),将其另存为文本,然后使用您用于attachments.add的字符串的保存位置

Dim wbkthis As Workbook
Dim wbkNew As Workbook

Set wbkthis = ActiveWorkbook 
'So we can come back here
Set wbkNew = Workbooks.Add 
'New book to copy sheet to

wbkthis.Sheets("relevantsheetname").Copy Before:=wbkNew.Sheets(1)

Application.DisplayAlerts = False
'Supress overwrite and close alerts, you may not want this

wbkNew.SaveAs "savelocation\Mybookname.txt", xlText 
'use this same string with your attachments.add code
wbkNew.Close

Application.DisplayAlerts = True
wbkthis.Activate ' Go back to original file

答案 2 :(得分:0)

我确信Axel的答案可能就是你所需要的,但是既然你问过要将它转换成文本然后再加入,那么就可以做到这一点。当然,格式化看起来很糟糕。确保(在VBE中)进入工具/引用并在Microsoft Forms 2.0对象库旁边放置一个复选框。

Dim ws As Worksheet
Dim DataObj As MSForms.DataObject
Set DataObj = New MSForms.DataObject
Set ws = ActiveWorkbook.ActiveSheet
    ws.UsedRange.Copy
DataObj.GetFromClipboard
strbody = DataObj.GetText(1)

With NewMail
  .SUBJECT = "Test Mail"
  .From = """Sender"" <sender@email.com>"
  .To = "receiver@email.com"
  .CC = ""
  .BCC = ""
  .TextBody = strbody
End With