我有一个在我的Outlook会话上运行的VB脚本,它监视每个新的电子邮件,并在收到特定的电子邮件地址和主题时触发 . 然后它保存该电子邮件中的附件并触发excel宏运行 .
当我测试这个(通过自己从另一个电子邮件地址发送电子邮件)它工作正常 . 今天早上,我的电脑收到了电子邮件(但电脑被“锁定”,Windows 7),但脚本没有被触发 . 我知道vba应该在后台工作,即使计算机被“锁定”,所以我很困惑为什么这个脚本没有触发 .
尽管计算机是否被锁定,我的VBA脚本是不是经常在后台运行?
这是代码:
从example@example.com接收电子邮件时触发宏“go”并且subject =今天
Private Sub Application_NewMailEx(ByVal EntryIDCollection As String)
'This sub catches every new email (or collection of emails)
Dim intMsgIDStart As Integer, intMsgIDEnd As Integer
Dim strMailItemID As String
Dim cont As Boolean
intMsgIDStart = 1
intMsgIDEnd = InStr(intMsgIDStart, EntryIDCollection, ",")
cont = True
Do
If (intMsgIDEnd > 0) Then
strMailItemID = Strings.Mid(EntryIDCollection, intMsgIDStart, (intMsgIDEnd - intMsgIDStart))
Else
strMailItemID = EntryIDCollection
End If
cont = handleMessage(strMailItemID)
intMsgIDStart = intMsgIDEnd + 1
intMsgIDEnd = InStr(intMsgIDStart, EntryIDCollection, ",")
Loop While intMsgIDEnd <> 0 And cont
End Sub
Public Function handleMessage(strMailItemID As String)
' This function takes an email ID and determines whether it's our pricing sheet email.
' If so, it'll save it to the folder with a common name, pricing.xls
' Finally, it will call on runExcelMacro()
On Error Resume Next
Dim mailItem As Outlook.mailItem
Dim path As String
Dim result As Boolean
result = True
Set mailItem = Application.Session.GetItemFromID(strMailItemID)
If (mailItem.SenderEmailAddress = "example@example.com" And Strings.Mid(mailItem.Subject, 1, 5) = "Today") Then
path = "C:\path\Pricing.xls"
mailItem.Attachments.item(1).SaveAsFile path
Call runExcelMacro("C:\path\Auto.xlsm", "go")
result = False
End If
handleMessage = result
End Function
Public Function runExcelMacro(path As String, macroName As String)
'This function starts a macro
Dim xl As Object
Set xl = CreateObject("Excel.Application")
xl.Workbooks.Open (path)
'xl.Visible = False
xl.Run macroName
xl.ActiveWorkbook.Close (True)
xl.Quit
Set xl = Nothing
End Function
也许我需要使用不同的设置让VBA始终在后台运行?
谢谢,并且道歉我的问题没有像我想的那样明确定义 - 我甚至不确定是什么问题!
干杯,
扎克
1 回答
收件箱中收到新项目时会触发NewMailEx事件 . 以下是MSDN声明的事件:
无论如何,我建议改为制定规则 . 然后,您可以将VBA子分配给规则 . VBA sub应如下所示:
邮件对象表示传入Outlook项目的位置 . 正如您所看到的,不需要使用GetItemFromId方法以编程方式获取传入的邮件项 .
此外,我建议选择另一个驱动器来保存附件 . 在最近的OS中,C:驱动器需要管理员权限才能写入 .