简体   繁体   English

Office 2010 VBA - 将 SenderEmailAddress 传递给 Excel 工作簿并运行 Excel 宏来发送电子邮件

[英]Office 2010 VBA - pass SenderEmailAddress to Excel workbook and run Excel macro to send email

I've been asking people that are more familiar with VBA than I with not the kind of luck that I am hoping for.我一直在问那些比我更熟悉 VBA 的人,但没有我希望的那种运气。 Here's what I need:这是我需要的:

  • incoming email with "Stats1", "Stats2", "Stats3" (etc.) in the subject line主题行中带有“Stats1”、“Stats2”、“Stats3”(等)的传入电子邮件
  • rule is triggered, capture the sender's email address触发规则,捕获发件人的电子邮件地址
  • open workbook and pass the email address to the workbook (example: emaillog.xlsm)打开工作簿并将电子邮件地址传递给工作簿(例如:emaillog.xlsm)
  • append to workbook (not overwrite)附加到工作簿(不覆盖)
  • log the email address, time and date on "emaillog.xlsm"在“emaillog.xlsm”上记录电子邮件地址、时间和日期
  • run an excel script (example emailsend.xlsm)运行一个 excel 脚本(例如 emailsend.xlsm)
  • send range of data from "emailsend.xlsm" to most recent entry on "emaillog.xlsm"将数据范围从“emailsend.xlsm”发送到“emaillog.xlsm”上的最新条目
  • save and close "emaillog.xlsm"保存并关闭“emaillog.xlsm”

Here's what I have for the Excel part to send:这是我要发送的 Excel 部分:

Public dTime As Date
Sub AutoSchedule1()
    dTime = Now() + TimeValue("01:00:00")
    Sheet("Sheet1").Range("u1").Value = "Email On, next send at " & Hour(dTime) & ":" & Minute(dTime)
    ActiveWorkbook.RefreshAll
    Application.OnTime dTime, "SendStatsTeam"
    If Hour(dTime) >= 18 Then
        Application.OnTime dTime, "SendStatsTeam", , False
        Exit Sub
    End If
End Sub
Sub SendStatsTeam()
    Dim AWorksheet As Worksheet
    Dim Sendrng As Range
    Dim rng As Range
    Dim Hournow As Long
    AutoSchedule1
    On Error GoTo StopMacro
    If Hour(Now()) > 12 Then
    Hournow = Hour(Now()) - 12
    Else
    Hournow = Hour(Now())
    End If
    With Application
        .ScreenUpdating = False
        .EnableEvents = False
    End With

    Set Sendrng = Worksheets("Sheet1").Range("A1:Z26")

    Set AWorksheet = ActiveSheet

    With Sendrng

        ActiveWorkbook.EnvelopeVisible = True
        With .Parent.MailEnvelope

            .Introduction = "Here are your stats"

            With .Item
                .To = SenderEmailAddress
                .CC = ""
                .BCC = ""
                .Subject = "Stats so far today" & Hour(Now()) & ":" & Application.WorksheetFunction.Text(Minute(Now()), "00")
                .Send
            End With

        End With

        rng.Select
    End With

    AWorksheet.Select

StopMacro:
    With Application
        .ScreenUpdating = True
        .EnableEvents = True
    End With
    ActiveWorkbook.EnvelopeVisible = False

End Sub

Sub emailoff()
Application.OnTime dTime, "SendStatsTeam", , False
    Worksheets("Sheet2").Range("u1").Value = "Email Off"
End Sub

I realize that I have not done everything correctly here as I'm fairly new to VBA but I have tried everything that I can to figure out the Outlook part.我意识到我在这里没有正确完成所有事情,因为我对 VBA 还很陌生,但我已经尽我所能来弄清楚 Outlook 部分。

Any help would be appreciated - I don't mind doing the reading I'm just at a point that I can't figure out what/where to go for the next part.任何帮助将不胜感激 - 我不介意阅读我只是在我无法弄清楚下一部分去哪里/去哪里的时候。

If you choose to help, I would like to add the ability to send different ranges of different sheets based on the subject of the email.如果您选择提供帮助,我想添加根据电子邮件主题发送不同范围的不同工作表的功能。

Thanks谢谢

Initial posting初始过帐

This is not an answer.这不是一个答案。 It is partly a request for clarification and partly a reference to an earlier answer which I believe will help you progress.这部分是对澄清的要求,部分是对我相信会帮助您进步的早期答案的参考。

There is little difference between a VBA macro written for Outlook and one written for Excel.为 Outlook 编写的 VBA 宏和为 Excel 编写的宏之间几乎没有区别。 Is there a reason why you want to run an Excel macro from Outlook?您是否有理由希望从 Outlook 运行 Excel 宏? It would be easier to include the macro without Outlook.在没有 Outlook 的情况下包含宏会更容易。 For example something like this:例如这样的事情:

  • New item event macro triggered by new email.新邮件触发的新项目事件宏。
  • Macro checks for subject.宏检查主题。
  • If subject is a keyword, open appropriate Excel workbook, store details of email, create reply from information in workbook and close workbook.如果主题是关键字,则打开适当的 Excel 工作簿,存储电子邮件的详细信息,根据工作簿中的信息创建回复并关闭工作簿。
  • Move processed emails to archive folder.将处理过的电子邮件移动到存档文件夹。

In response to earlier questions, I created a macro that demonstrates writing to Excel from Outlook.为了回答之前的问题,我创建了一个宏来演示从 Outlook 写入 Excel。 That macro does not match your requirement but demonstrates lots of techniques that will be relevant.该宏不符合您的要求,但演示了许多相关的技术。 Click https://stackoverflow.com/a/12146315/973283 to visit that answer.单击https://stackoverflow.com/a/12146315/973283访问该答案。

I hope the above points are helpful.我希望以上几点有帮助。 Do come back with clarifications or further questions as necessary.如有必要,请务必回来澄清或提出进一步的问题。

Posting 2 after the requirement for clarified需求明晰后发帖2

This next part of the answer is later than I hoped.答案的下一部分比我希望的要晚。 Partly because it has been a busy day and partly because I encountered a problem I had not expected.部分是因为这是忙碌的一天,部分是因为我遇到了一个我没有预料到的问题。

From within Outlook select the Visual Basic Editor by: - selecting Tools then Macro then Visual Basic Editor or - clicking Alt+F11.从 Outlook 中通过以下方式选择 Visual Basic 编辑器: - 依次选择工具、宏和 Visual Basic 编辑器或 - 单击 Alt+F11。

Down the left will be the Project Explorer which could be:左下方将是 Project Explorer,它可能是:

- Project1 (VbaProject.OTM)
  + Microsoft Outlook Objects
  + Forms
  + Modules

If you have no forms or modules, these entries will be missing.如果您没有表单或模块,这些条目将丢失。 Any entries that are present may already be expanded.任何存在的条目可能已经被展开。 Expand Microsoft Outlook Objects , if not already expanded, by clicking the + .单击+展开Microsoft Outlook Objects (如果尚未展开)。 The display will change to:显示将变为:

- Project1 (VbaProject.OTM)
  - Microsoft Outlook Objects
      ThisOutlookSession
  + Forms
  + Modules

Click ThisOutlookSession .单击ThisOutlookSession The top right area will become white (if it is not already white).右上角区域将变为白色(如果它还不是白色)。 This is a code area, like a module, but is for special code.这是一个代码区,就像一个模块,但用于特殊代码。

Paste the code below into the ThisOutlookSession code area.将下面的代码粘贴到ThisOutlookSession代码区域。

This code contains two macros.此代码包含两个宏。 The first macro, Application_Startup(), is automatically executed when Outlook is opened.第一个宏 Application_Startup() 在打开 Outlook 时自动执行。 It specifies that the arrival of a new item in the Inbox is to trigger a call of macro myNewItems_ItemAdd() .它指定收件箱中新项目的到达将触发宏myNewItems_ItemAdd()的调用。 It also outputs "Welcome" to demonstrate that it has been called.它还输出“欢迎”以证明它已被调用。 The second macro, myNewItems_ItemAdd() identifies the type of the new item and outputs selected information to the Immediate Window.第二个宏myNewItems_ItemAdd()标识新项目的类型并将所选信息输出到立即窗口。

These macros execute correctly but there is a problem I have not solved.这些宏正确执行,但有一个我没有解决的问题。 Outlook correctly, in my view, is unhappy about macros and macros that access emails in particular.在我看来,Outlook 对宏和访问电子邮件的宏并不满意。 When you open Outlook it tells you there are macros (providing you have an adequate security level) and offers you the option of enabling or disabling those macros.当您打开 Outlook 时,它会告诉您有宏(前提是您具有足够的安全级别)并为您提供启用或禁用这些宏的选项。 If a macro attempts to access an email, Outlook warns you and offers the option of permitting access for up to 10 minutes.如果宏尝试访问电子邮件,Outlook 会警告您并提供最多允许访问 10 分钟的选项。

I have self-certified these macros which tells Outlook I trust them.我已经对这些宏进行了自我认证,这告诉 Outlook 我信任它们。 This suppresses the warning about macros being present but does not, as I expected, suppress the warning about a macro attempting to access emails.这会抑制有关存在宏的警告,但不会像我预期的那样抑制有关尝试访问电子邮件的宏的警告。 I will investigate further for my own interest but having to be ready to give permission every 10 minutes defeats the objective of you having a new item event.我会为了我自己的利益而进一步调查,但必须准备好每 10 分钟给予许可,这违背了您举办新项目活动的目标。

I suggest you play with these macros anyway because knowing this functionality exists may be helpful later.我建议您无论如何都使用这些宏,因为知道此功能存在可能会在以后有所帮助。

I can think of three situations:我可以想到三种情况:

  • If you work for a large company with an IT department, you probably cannot self-certify anyway because you need administrative privileges to do so.如果您在拥有 IT 部门的大公司工作,您可能无论如何都无法进行自我认证,因为您需要管理权限才能这样做。 You will need to seek the advice of the IT Department.您需要寻求 IT 部门的建议。
  • If I cannot identify how to suppress the requirement to give permission every 10 minutes, perhaps someone else on Stack Overflow can.如果我无法确定如何抑制每 10 分钟授予权限的要求,那么 Stack Overflow 上的其他人也许可以。
  • Once per hour, say, you could run a macro which would look for any request emails that had arrived since the last run.例如,每小时一次,您可以运行一个宏来查找自上次运行以来收到的任何请求电子邮件。 If the macro found any, you would give permission for it to process them.如果宏找到任何内容,您将授予它处理它们的权限。 If this approach appeals, I definitely know how to implement such a macro.如果这种方法有吸引力,我绝对知道如何实现这样的宏。

. .

 Option Explicit
 Public WithEvents MyNewItems As Outlook.Items
 Private Sub Application_Startup()

   ' This event procedure is called when Outlook is started

   Dim NS As NameSpace

   Set NS = CreateObject("Outlook.Application").GetNamespace("MAPI")

   With NS
    Set MyNewItems = NS.GetDefaultFolder(olFolderInbox).Items
   End With

   MsgBox "Welcome"

 End Sub
 Private Sub myNewItems_ItemAdd(ByVal Item As Object)

   ' This event procedure is called whenever a new item is added to
   ' to the InBox.

   Dim NewMailItem As MailItem

   Debug.Print "------Item Received"

   On Error Resume Next
   ' This will give an error and fail to set NewMailItem if
   ' Item is not a MailItem.
   Set NewMailItem = Item
   On Error GoTo 0

   If Not NewMailItem Is Nothing Then
     ' This item is a mail item
     With NewMailItem
       Debug.Print "Subject " & .Subject
       Debug.Print "Sender Email [" & .SenderEmailAddress & "]"
     End With
   Else
     ' Probably a meeting request.
     Debug.Print "Not mail item " & Item.Subject
   End If

 End Sub

For my next posting, I will add an Outlook macro that opens a workbook and writes to it and reads from it.对于我的下一个帖子,我将添加一个 Outlook 宏,该宏可以打开一个工作簿并写入它并从中读取。

In your question you say you want to send a range from the workbook to the author of the email.在您的问题中,您说要将工作簿中的范围发送给电子邮件的作者。 Do you know how to do this?你知道怎么做吗? If not what sort of range would you send?如果不是,你会发送什么样的范围? How would you want it to appear?你希望它如何出现? Converting a small range to Html is not difficult if that would give you the appearance you seek.如果这会给您想要的外观,那么将小范围转换为 Html 并不困难。

Final posting最终发布

Sorry but I am giving up on this question.抱歉,我放弃了这个问题。 Nothing I have tried prevents Outlook from reporting that a macro is trying to send an email.我没有尝试阻止 Outlook 报告宏正在尝试发送电子邮件。 Everything else about this question is straightforward but this issue is a killer.关于这个问题的其他一切都很简单,但这个问题是一个杀手。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM