[英]How to fix Compile Error: User-defined type not defined when using Excel VBA from Outlook?
[英]Sending Outlook Email Using Excel VBA generates error: user-defined type not defined
我正在嘗試通過Outlook從Excel 2010發送電子郵件。
Outlook已打開,我已選擇對Outlook 14.0的引用
我創建了一個名為SendEmail的宏:
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
我創建了另一個名為SendMassEmail()的宏:
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
當我運行代碼時,它會出現以下錯誤:
用戶定義類型未定義
您已經檢查了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
創建方式,因此,如果您已經在運行另一個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
我建議第一個解決方案。 因為這樣您才能導入庫,因此它會“更好”地工作,並且每次使用Outlook對象時,您都可以看到對象的屬性列表。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.