Excel VBA 错误"user-defined type not defined"与 Outlook



>我在计算机中使用Office 2016,并且我有一个VBA代码,可以将电子邮件发送到文件中的邮件列表。每次我想使用命令按钮自动发送电子邮件时,我都会收到错误按摩:"未定义用户定义的类型"。我在网上做了一些研究,我发现有一个解决方案:----> Microsoft Outlook 16.0 对象库中引用的 VB 编辑器---->工具---->

下次我打开文件时,同样的错误一次又一次地运行。有人能为我找到永久的解决方案吗?我不知道该做什么,然后我已经做了。

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

正如我在注释中建议的那样,您可以像下面这样编辑代码(请参阅三个注释行(,并且应该能够在没有引用的情况下运行。我假设代码是正确的,否则它提供了预期的结果

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

后期绑定在其他一些情况下也有帮助,特别是如果有多个用户并且他们在软件版本方面有不同的设置!

最新更新