在Excel中发送群发邮件使用VBA
我正在尝试通过Outlook从我的Excel发送电子邮件。
我正在使用Excel 2010,Outlook已打开,并select了对Outlook 14.0的引用
我创build了一个名为SendEmail的macros,并input了以下代码:
Sub SendEmail(what_address As String, subject_line As String, mail_body As String) Dim olApp As Outlook.Application Set olApp = CreateObject("outlook.Application") Dim olMail As Outlook.MailItem Set olMail = olApp.CreateItem(olMailItem) olMail.To = what_address olMail.Subject = subject_line olMail.body = mail_body olMail.Send End Sub
然后我创build了称为SendMassEmail()的其他macros。 并input下面的代码:
Sub SendMassEmail() row_number = 1 Do DoEvents row_number = row_number + 1 'MegBox (Sheet.Range("J3")) Call SendEmail(Sheet1.Range("A" & row_number), "THis is a test email", Sheet1.Range("J2")) Loop Until row_number = 4 'Range("A" & Rows.Count).End(xlUp).Row End Sub
但是,当我运行代码,它出现了以下错误:用户定义types未定义
你能不能让我知道如何解决它?
由于您已经检查了Microsoft Outlook 14.0对象库参考,
你可以尝试像这样迟到:
Sub SendEmail(what_address As String, subject_line As String, mail_body As String) Dim olApp As Object Dim olMail As Object On Error Resume Next Set olApp = GetObject(, "Outlook.Application") If Err.Number>0 Then Set olApp = CreateObject("Outlook.Application") On Error Goto 0 Set olMail = olApp.CreateItem(0) olMail.To = what_address olMail.Subject = subject_line olMail.body = mail_body olMail.Send End Sub
我更改了olApp
创build,所以如果您已经有一个Outlook正在运行,您不会创build另一个Outlook实例! ;)
您可以使用以下代码,但需要添加对Microsoft Outlook 14.0对象库(工具 – >引用…)的引用:
Sub SendEmail(what_address As String, subject_line As String, mail_body As String) Dim olApp As Outlook.Application Set olApp = New Outlook.Application Dim olMail As Outlook.MailItem Set olMail = olApp.CreateItem(olMailItem) olMail.To = what_address olMail.Subject = subject_line olMail.body = mail_body olMail.Send End Sub
还有另外一种方法可以在不导入库的情况下做到这一点
Sub SendEmail(what_address As String, subject_line As String, mail_body As String) Dim olApp As Object Set olApp = CreateObject("Outlook.Application") Dim olMail As Object Set olMail = olApp.CreateItem(olMailItem) olMail.To = what_address olMail.Subject = subject_line olMail.body = mail_body olMail.Send End Sub
我会build议第一个解决scheme。 因为那么你正在导入它“工作得更好”的库,每当你使用Outlook对象时,你都可以看到对象的属性列表。