我在计算机中使用Office 2016,并且我有一个VBA代码,可以将电子邮件发送到文件中的邮件列表。每当我想用我的CommandButton自动发送电子邮件时,我得到错误按摩:“用户定义的类型未定义”。 我在网上做了一些研究,我发现有一个解决方案: VB编辑器---->工具---->参考----> Microsoft Outlook 16.0对象库
但是 下次打开文件时,同样的错误会一次又一次地运行。有人能找到我永久的解决方案吗?我不知道该怎么做,然后我已经做了。
Public Sub sendMail()
Call ini_set
If mail_msg.Cells(200, 200) = 1 Then
lr = main_dist.Cells(main_dist.Rows.Count, "A").End(xlUp).row
On Error Resume Next
For i = 2 To lr
Application.DisplayAlerts = False
Dim applOL As Outlook.Application
Dim miOL As Outlook.MailItem
Dim recptOL As Outlook.Recipient
mail_msg.Visible = True
mailSub = mail_msg.Range("B1")
mailBody = mail_msg.Range("B2")
mail_msg.Visible = False
Set applOL = New Outlook.Application
Set miOL = applOL.CreateItem(olMailItem)
Set recptOL = miOL.Recipients.Add(main_dist.Cells(i, 5))
recptOL.Type = olTo
tempPath = ActiveWorkbook.Path & "\" & main_dist.Cells(i, 4) & ".xlsm"
With miOL
.Subject = mailSub
.Body = mailBody
.Attachments.Add tempPath
.send
End With
Set applOL = Nothing
Set miOL = Nothing
Set recptOL = Nothing
Application.DisplayAlerts = True
Next i
End Sub
以下是基于VB编辑器的问题:
Dim applOL As Outlook.Application
答案 0 :(得分:1)
正如我在评论中建议的那样,您可以像下面一样编辑代码(请参阅三条注释行),并且应该能够在没有引用的情况下运行。 我假设代码是正确的,否则它提供了预期的结果
Public Sub sendMail()
Call ini_set
If mail_msg.Cells(200, 200) = 1 Then
lr = main_dist.Cells(main_dist.Rows.Count, "A").End(xlUp).Row
On Error Resume Next
For i = 2 To lr
Application.DisplayAlerts = False
Dim applOL As Object '\\Outlook.Application
Dim miOL As Object '\\Outlook.MailItem
Dim recptOL As Object '\\Outlook.Recipient
mail_msg.Visible = True
mailSub = mail_msg.Range("B1")
mailBody = mail_msg.Range("B2")
mail_msg.Visible = False
Set applOL = New Outlook.Application
Set miOL = applOL.CreateItem(olMailItem)
Set recptOL = miOL.Recipients.Add(main_dist.Cells(i, 5))
recptOL.Type = olTo
tempPath = ActiveWorkbook.Path & "\" & main_dist.Cells(i, 4) & ".xlsm"
With miOL
.Subject = mailSub
.Body = mailBody
.Attachments.Add tempPath
.send
End With
Set applOL = Nothing
Set miOL = Nothing
Set recptOL = Nothing
Application.DisplayAlerts = True
Next i
End Sub
后期绑定在其他一些情况下也有帮助,特别是如果有多个用户,并且他们在软件版本方面有不同的设置!