【发布时间】:2019-09-03 03:23:49
【问题描述】:
我一直在使用 vba 为 excel 进行电子邮件自动化,我的代码仅适用于第一封电子邮件,并且在下一封邮件中出现运行时错误,
我尝试将对象设置为无济于事..
我不知道内存泄漏在哪里
有人能指点一下吗
错误出现在对象备注处。我已经提供了错误的屏幕截图..
模块名称 = 自动邮件
Public PublicRow As Integer
Dim mark As New Remarks
Sub Button_Click()
Dim LastR As Long
Dim CRow As Long
Dim sSendTo As String
Dim sSendCC As String
Dim sSendBCC As String
Dim sSubject As String
Dim txt As String
Dim OutApp As Object
Dim OutMail As Object
Set OutApp = CreateObject("Outlook.Application")
Set mark.item = Nothing
OutApp.Session.Logon
LastR = Cells(Rows.Count, 2).End(xlUp).Row
For CRow = 3 To LastR
If Cells(CRow, 6) <> "Email sent" Then
If Cells(CRow, 3) <= Date Then
Set OutMail = OutApp.CreateItem(0)
Set mark.item = OutMail
sSendTo = Cells(CRow, 5)
sSendCC = ""
sSendBCC = ""
sSubject = "Project Due Date"
PublicRow = CRow
With OutMail
.To = sSendTo
If sSendCC > "" Then .CC = sSendCC
If sSendBCC > "" Then .BCC = sSendBCC
.Subject = sSubject
txt = "Dear " & Cells(CRow, 4) & ", "
txt = txt & vbCrLf & vbCrLf
txt = txt & "The due date has been reached for the
project:"
txt = txt & vbCrLf & vbCrLf
txt = txt & " " & Cells(CRow, 2)
txt = txt & vbCrLf & vbCrLf
txt = txt & "Please take the appropriate actions."
txt = txt & vbCrLf & vbCrLf
txt = txt & "Regards,"
txt = txt & vbCrLf
txt = txt & "Danial"
.Body = txt
.Display (True)
End With
Set OutMail = Nothing
End If
End If
Next CRow
Set mark.item = Nothing
Set OutApp = Nothing
End Sub
类名 = 备注
Option Explicit
Public WithEvents item As Outlook.MailItem
Private Sub item_Close(Cancel As Boolean)
Dim boolSent As Boolean
boolSent = item.Sent
If Err.Number = 0 Then
Cells(PublicRow, 6) = "Email not sent"
Cells(PublicRow, 7) = "X"
Else
Cells(PublicRow, 6) = "Email sent"
Cells(PublicRow, 7) = Now()
End If
End Sub
错误:
【问题讨论】:
-
把
Dim mark As New Remarks改成Dim mark As Remarks看看有什么变化。我猜您将mark设置为空,但由于您使用New关键字,它会立即再次实例化。见这里:stackoverflow.com/a/42656772/10223558 -
如果不需要,您也可以省略整个 CC 和 BCC 内容,使代码更具可读性。像 outApp 一样将
mark移动到 Method 内部,然后它会在 Method 结束时超出范围,您不必= Nothing它。 -
嗨 L8n,通过从声明中删除 New。宏不将备注声明为对象并返回不存在错误。但是在错误之后,重新编写“New”。 The code runs fine.. i noticed that the code runs fine when the pop out windows of selecting outlook profile is gone.. So i think i have to do with the popup windows itself that block the email from being detected by my Remarks class
标签: excel vba outlook runtime-error