excel - VBA 应用程序定义的错误 Outlook 连接

标签 excel vba outlook late-binding

我有以下代码,但一直出现错误“应用程序定义或对象定义错误”,并且无法理解原因。 Microsoft Office 16.0 对象库工具已激活,我确信该错误与 Set OutlookMail = OutlookApp.CreateItem(0) 行类似。当然,我遗漏了一些与 Outlook 有关的内容。

Sub send_emails()

Dim outlookApp As Object
Dim outlookMail As Object
Dim cell As Range
Dim lastRow As Long

' Create Outlook object
Set outlookApp = CreateObject("Outlook.Application")

' Determine the last row in the worksheet
lastRow = ActiveSheet.Cells(Rows.Count, "A").End(xlUp).Row

' Loop through each cell in column D
For Each cell In Range("D2:D" & lastRow)
  
  ' Check if the date in the cell is 15 days from today
  If cell.Value = Date + 15 Then
    
    ' Retrieve the corresponding email address, name, and surname
    Email = cell.Offset(0, 2).Value
    Name = cell.Offset(0, 1).Value
    surname = cell.Offset(0, -1).Value
    
    ' Create a new email
    Set outlookMail = outlookApp.CreateItem(0)
    
    ' Set the recipient, subject, and body of the email
    outlookMail.To = Email
    outlookMail.Subject = "Reminder"
    outlookMail.Body = "Dear " & Name & " " & surname & ", this is a reminder that your event is coming up in 15 days. Please make sure to prepare accordingly."
    
    ' Set the sender and send the email
    outlookMail.SendUsingAccount = outlookApp.Session.Accounts.Item("YOUR EMAIL ADDRESS")
    outlookMail.Send
    
    ' If the email was sent successfully, color the cell in column E green
    cell.Offset(0, 1).Interior.Color = vbGreen
  End If
Next cell

' Clean up
Set outlookMail = Nothing
Set outlookApp = Nothing

End Sub

最佳答案

The tool Microsoft Office 16.0 Object library is activated

我想您已经在 Excel VBA 环境中添加了对 Outlook 对象模型(COM 引用)的引用。在代码中我看到使用了后期绑定(bind)技术:

Dim outlookApp As Object
Dim outlookMail As Object
' Create Outlook object
Set outlookApp = CreateObject("Outlook.Application")

但同时您添加了一个 COM 对象引用,以便在代码中使用早期绑定(bind)。因此,我建议使用 New 运算符并在代码中声明具有特定类型的所有 Outlook 对象:

Dim outlookApp As Outlook.Application
Dim outlookMail As Outlook.MailItem

Set outlookApp = New Outlook.Application()

您可以在Using early binding and late binding in Automation中阅读有关早期和后期绑定(bind)技术的更多信息。文章。

关于excel - VBA 应用程序定义的错误 Outlook 连接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/75040141/

相关文章:

vba - 将数组放入 class.property

excel - 每 5 行隐藏 4 个

excel - 在 VBA 中使用 .NET HashTable 返回类型

outlook - "Outlook blocked access to the following potentially unsafe attachments"

c# - OleDbConnection 仅当工作簿也在 Excel 中打开时才查找单元格值

从列表中随机选择

excel - 在 VBA 中打开与 Excel 电子表格的 ADO 连接

vba - 从电子表格引用单元格并填充相应的单元格

c# - 访问 Outlook ost 文件

vba - 将 Outlook 电子邮件另存为 PDF + 附件