将包含代码的 Excel 文件作为附件发送 [英] Sending Excel file, that contains the code, as an attachment

查看:29
本文介绍了将包含代码的 Excel 文件作为附件发送的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我编写了通过 Outlook 发送电子邮件的 Excel VBA 代码.

I've written Excel VBA code that sends an email via Outlook.

我看过的所有地方,用于将文件附加到电子邮件的示例代码都是针对静态命名文件的,例如,您每次都发送相同的文件名和相同的路径.

Everywhere I've looked, example code for attaching files to an email is for static named files, as in, you're sending the same file name, with the same path every time.

运行此宏的按钮位于我尝试附加的工作簿内.

The button that runs this macro is inside the workbook that I'm trying to attach.

Sub mySub
    Dim objOutlook As Outlook.Application
    Dim objOutlookMsg As Outlook.MailItem
    Dim objOutlookRecip As Outlook.recipient
    Dim objOutlookAttach As Outlook.Attachment
    Dim WeekendingDate As Date
    
    With Worksheets("Macro Buttons")
        WeekendingDate = Range("N2").Value
    End With
    
    Set objOutlook = CreateObject("Outlook.Application")
    
    Set objOutlookMsg = objOutlook.CreateItem(olMailItem)
    
    With objOutlookMsg
        Set objOutlookRecip = .Recipients.Add("blah@blah")
        objOutlookRecip.Type = olTo
       .Subject = "Blah " & WeekendingDate
       .Body = "blah blah blah"
       
       'Add attachments to the message
       [some code]
    
    
       For Each objOutlookRecip In .Recipients
           objOutlookRecip.Resolve
       Next
       If DisplayMsg Then
           .Display
       Else
           .Save
       End If
    End With
    Set objOutlook = Nothing
End Sub

推荐答案

您需要将 Attachments.Add 代码插入到 MailItem 设置中:

You need the Attachments.Add code inserted into the MailItem setup:

With objOutlookMsg
    Set objOutlookRecip = .Recipients.Add("blah@blah")
    objOutlookRecip.Type = olTo
   .Subject = "Blah " & WeekendingDate
   .Body = "blah blah blah"
'Add attachments to the message [some code]
   .Attachments.Add "pathToFile"
   For Each objOutlookRecip In .Recipients
       objOutlookRecip.Resolve
   Next
   If DisplayMsg Then
       .Display
   Else
       .Save
   End If
End With
Set objOutlook = Nothing

在我自己的一个脚本中,我将一组附件传递给要使用 Dictionary 对象和以下代码附加的 MailItem:

In one of my own scripts I pass a collection of attachments to the MailItem to be attached using a Dictionary object and the following code:

With oMailItem
        Set .SendUsingAccount = oOutlook.Session.Accounts.Item(iAccount)
        .To = EmailData("To")
        .CC = EmailData("CC")
        .BCC = EmailData("BCC")
        .Subject = EmailData("Subject")
        .Body = EmailData("Body")
        sAttachArray = Split(EmailData("AttachmentPaths"), ";")
        For Each sAttachment In sAttachArray
            .Attachments.Add(sAttachment)
        Next
        .Recipients.ResolveAll
        .Display    ' debug mode - uncomment this to see email before it's sent out
    End With

这篇关于将包含代码的 Excel 文件作为附件发送的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆