Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> ซอฟต์แวร์ >> Office

ส่งอีเมลจาก Excel โดยใช้ VBA Macro และ Outlook

ฉันได้รับมอบหมายให้ส่งอีเมลไปยังผู้ใช้ที่แสดงรายชื่อในสเปรดชีต Excel แต่ละอีเมลต้องมีข้อมูลบางอย่างที่เป็นของแต่ละบุคคล ฉันลองทำโดยใช้ VBA macro ใน Excel ที่ส่งอีเมลจากโปรไฟล์ Outlook ที่ตั้งค่าไว้บนคอมพิวเตอร์ นี่คือโซลูชันของฉัน

สมมติว่าคุณมีไฟล์ Excel ด้วยคอลัมน์ต่อไปนี้:

Email | Full Name | Last Password Change Date | Account status

ส่งอีเมลจาก Excel โดยใช้ VBA Macro และ Outlook

ภารกิจของฉันคือส่งอีเมลแบบนี้จากเทมเพลตนี้ไปยังแต่ละผู้ใช้ในรายการ:

Subject: Your account status on woshub.com domain
Body: Dear %FullUsername%,
Your account in woshub.com domain is in %status% state
The date and time of the last password change is %pwdchange%

สร้างแมโครใหม่: View -> Macros ระบุชื่อแมโคร (send_email) และคลิก Create:

ส่งอีเมลจาก Excel โดยใช้ VBA Macro และ Outlook

คัดลอกและวางโค้ดต่อไปนี้ลงใน VBA editor ที่ปรากฏขึ้น (ฉันได้เพิ่มคอมเมนต์ที่เกี่ยวข้องแล้ว) เพื่อทำให้การส่งอีเมลเป็นอัตโนมัติ ฉันจะใช้ฟังก์ชัน CreateObject ("Outlook.Application") ที่อนุญาตให้สร้างและใช้วัตถุ Outlook ภายในสคริปต์ VBA

สำคัญ โปรไฟล์ Outlook ต้องได้รับการตั้งค่าบนคอมพิวเตอร์ส่ง อีเมลบ็อกซ์นี้ (และที่อยู่อีเมล) จะถูกใช้เพื่อส่งอีเมล

Sub send_email()
Dim olApp As Object
Dim olMailItm As Object
Dim iCounter As Integer
Dim Dest As Variant
Dim SDest As String
' Subject
strSubj = "Your account status on woshub.com domain"
On Error GoTo dbg
' Create a new Outlook object
Set olApp = CreateObject("Outlook.Application")
For iCounter = 1 To WorksheetFunction.CountA(Columns(1))
' Create a new item (email) in Outlook
Set olMailItm = olApp.CreateItem(0)
strBody = ""
useremail = Cells(iCounter, 1).Value
FullUsername = Cells(iCounter, 2).Value
Status = Cells(iCounter, 4).Value
pwdchange = Cells(iCounter, 3).Value
'Make the body of an email
strBody = "Dear " & FullUsername & vbCrLf
strBody = strBody & " Your account in woshub.com domain is in" & Status & " state" & vbCrLf
strBody = strBody & "The date and time of the last password change is" & pwdchange & vbCrLf
olMailItm.To = useremail
olMailItm.Subject = strSubj
olMailItm.BodyFormat = 1
' 1 – text format of an email, 2 - HTML format
olMailItm.Body = strBody
olMailItm.Send
Set olMailItm = Nothing
Next iCounter
Set olApp = Nothing
dbg:
'Display errors, if any
If Err.Description <> "" Then MsgBox Err.Description
End Sub

ส่งอีเมลจาก Excel โดยใช้ VBA Macro และ Outlook

บันทึกไฟล์ Excel นี้เป็น .xlsm (รูปแบบสมุดงาน Excel ที่รองรับแมโคร) เพื่อส่งอีเมล ให้เลือกกระบวนการที่สร้างขึ้น (แมโคร) และคลิก Run

ส่งอีเมลจาก Excel โดยใช้ VBA Macro และ Outlook

แมโครจะวนลูปผ่านทุกแถวบนเวิร์กชีต Excel ทีละแถว สร้างและส่งอีเมลไปยังแต่ละผู้รับในรายการ