Excel VBA: 在 Outlook 电子邮件创建子例程中停止工作

Excel VBA: Stops Working at Outlook Email Creation Subroutine

前几天我问了这个问题并认为我找到了答案,但现在 Excel 一直进入 'Not Responding' 模式。我的问题是该程序 运行 在某些计算机上运行良好,但在其他计算机上却崩溃了。

背景: 该程序在用户填写 Excel 表单并单击提交后获得 运行。该程序验证数据、处理数据、通过 Outlook 创建电子邮件,最后保存并关闭文档。

该程序在工作中的许多同事的计算机上得到 运行。我们都运行 Windows 7,Office 2013,但我们中的一些人有不同的笔记本电脑(惠普、戴尔等)

这是对子例程的调用,这是 excel 开始到 'Not Respond' 的代码行 - 仅供参考,这 不是 调试停止:

Call EmailApprovalP1(GeneralSection, ItemSection, VendorSection, MarketSection, Part1Section, wbLog, wbPCD, resubmission)

这是被调用的子程序的开头:

Public Sub EmailApprovalP1(ByRef GeneralSection As Object, ByRef ItemSection As Object, ByRef VendorSection As Object, ByRef MarketSection As Object, ByRef Part1Section As Object, ByRef wbLog As Workbook, ByRef wbPCD As Workbook, ByRef resubmission As Boolean)

'Declare In Memory
Dim i As Integer
Dim toEmail As String
Dim subject As String
Dim body As String
Dim OL As New Outlook.Application
Dim olMail As Outlook.MailItem
Set olMail = OL.CreateItem(olMailItem)    

如果我在 Call EmailApprovalP1() 上停止代码然后按 F8,Excel 将停止响应。有没有人知道可能导致这种情况的原因?

更新 2-3-15

适用于所有计算机的代码

Dim OL As Object
Set OL = CreateObject("Outlook.Application")
Dim olMail As Object
Set olMail = OL.CreateItem(olMailItem)

使用 CreateObject 而不是 NewNew 已知会导致一些不稳定问题。

Dim OL As Outlook.Application
Set OL = CreateObject("Outlook.Application")

首先,请确保您在 运行 代码之前添加了对 Outlook 的引用。您需要在必须获取代码 运行 的每台 PC 上执行此操作。 How to automate Outlook from another program 文章介绍了从其他应用程序自动化 Outlook 所需的所有步骤。

如果没有帮助,请尝试单步执行 (F8) 函数并找到导致问题的确切代码行。

在内存中声明为 Object 而不是 Outlook.Application 有所不同。感谢您为我指明正确的方向@Eugene 和@Jeanno!

下面是有效的代码:

Dim OL As Object
Set OL = CreateObject("Outlook.Application")
Dim olMail As Object
Set olMail = OL.CreateItem(olMailItem)