怎么用VBA来发送邮件,需要源代码
时间: 2023-03-11 12:59:17 浏览: 93
首先,您需要添加 Outlook 对象,然后使用下面的代码来发送邮件:Dim OutApp As Object
Dim OutMail As Object
Set OutApp = CreateObject("Outlook.Application")
Set OutMail = OutApp.CreateItem(0)
On Error Resume Next
With OutMail
.To = "收件人地址"
.CC = ""
.BCC = ""
.Subject = "邮件主题"
.Body = "正文内容"
.Send ' 发送邮件
End With
On Error GoTo 0
Set OutMail = Nothing
Set OutApp = Nothing
相关问题
怎么用vba来发送邮件 需要源代码
可以通过使用VBA的Outlook应用程序来发送电子邮件,下面是示例源代码:Sub Send_Email()Dim OutApp As Object
Dim OutMail As ObjectSet OutApp = CreateObject("Outlook.Application")
Set OutMail = OutApp.CreateItem(0)With OutMail
.To = "receiver@domain.com"
.CC = ""
.BCC = ""
.Subject = "Test Email"
.Body = "This is a test message"
.Attachments.Add ("c:\test.txt")
.Send
End WithSet OutMail = Nothing
Set OutApp = NothingEnd Sub
基于判断发送邮件VBA代码
以下是一个基于判断的发送邮件VBA代码示例:
```VBA
Sub SendEmail()
Dim OutlookApp As Object
Dim OutlookMail As Object
Dim MyEmail As String
Dim RecipientEmail As String
Dim SubjectLine As String
Dim EmailBody As String
' Set up Outlook application
Set OutlookApp = CreateObject("Outlook.Application")
Set OutlookMail = OutlookApp.CreateItem(0)
' Set email properties
MyEmail = "your@email.com"
RecipientEmail = Range("A1").Value 'recipient email address in cell A1
SubjectLine = "Subject Line Text"
' Check if recipient email is valid
If InStr(RecipientEmail, "@") > 0 And InStr(RecipientEmail, ".") > 0 Then
' Email address is valid
EmailBody = "Email Body Text"
With OutlookMail
.To = RecipientEmail
.CC = ""
.BCC = ""
.Subject = SubjectLine
.Body = EmailBody
.Send
End With
MsgBox "Email sent successfully!", vbInformation
Else
' Email address is not valid
MsgBox "Invalid email address!", vbCritical
End If
Set OutlookMail = Nothing
Set OutlookApp = Nothing
End Sub
```
该代码从单元格 A1 中读取收件人电子邮件地址,并检查该地址是否有效。如果有效,则发送邮件,如果无效,则弹出错误消息框。您可以根据需要修改电子邮件正文和其他属性。