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

ส่งอีเมลจาก Excel ด้วย VBA Macro ผ่าน Outlook

สร้าง Macro ใน Excel เพื่อส่งอีเมลจำนวนมากไปยังรายชื่อใน Spreadsheet โดยใช้ Outlook Profile ที่ตั้งค่าไว้บนเครื่อง

ตัวอย่างข้อมูลใน Excel (Columns A-D)

Email | Full Name | Last Password Change Date | Account Status
user1@domain.com | John Doe | 2023-01-15 | Active
user2@domain.com | Jane Smith | 2023-02-20 | Expired

รหัส VBA (Alt+F11 > Insert Module)

Sub SendEmails()
    Dim olApp As Object, olMail As Object
    Dim i As Long, lastRow As Long
    Dim emailTo As String, fullName As String, pwdDate As String, status As String
    Dim subject As String, body As String
    
    Set olApp = CreateObject("Outlook.Application")
    subject = "Your account status on woshub.com domain"
    
    lastRow = Cells(Rows.Count, 1).End(xlUp).Row
    
    For i = 2 To lastRow ' Assume header in row 1
        emailTo = Cells(i, 1).Value
        fullName = Cells(i, 2).Value
        pwdDate = Cells(i, 3).Value
        status = Cells(i, 4).Value
        
        If emailTo <> "" Then
            Set olMail = olApp.CreateItem(0) ' olMailItem
            body = "Dear " & fullName & vbCrLf & _
                   "Your account in woshub.com domain is in " & status & " state" & vbCrLf & _
                   "The date and time of the last password change is " & pwdDate & vbCrLf
            
            With olMail
                .To = emailTo
                .Subject = subject
                .BodyFormat = 1 ' 1=Plain Text, 2=HTML
                .Body = body
                .Send
            End With
            Set olMail = Nothing
        End If
    Next i
    
    Set olApp = Nothing
    MsgBox "Emails sent successfully!"
End Sub

ขั้นตอนการใช้งาน

  1. เปิด Excel ไฟล์ที่มีข้อมูล
  2. กด Alt+F11 เปิด VBA Editor
  3. Insert > Module > วางโค้ดข้างต้น
  4. Save ไฟล์เป็น .xlsm (Macro-Enabled Workbook)
  5. กด Alt+F8 เลือก SendEmails > Run

ข้อกำหนดและข้อควรระวัง

  • ต้องมี Outlook Profile ตั้งค่าแล้ว บนเครื่อง (ใช้อีเมลนี้เป็น Sender)
  • Macro จะส่งอีเมลทีละฉบับ อาจช้าถ้ารายชื่อเยอะ
  • Outlook อาจแสดง Prompt "A program is trying to send email..." ตั้งค่า Trust Center > Programmatic Access > Allow หรือใช้ Digital Signature
  • ทดสอบกับข้อมูลน้อยก่อน (เช่น 2-3 ราย) เพื่อตรวจสอบรูปแบบอีเมล
  • สำหรับ HTML Email ให้เปลี่ยน .BodyFormat = 2 และใช้ .HTMLBody แทน .Body

ปรับแต่งเพิ่มเติม

  • เพิ่ม Attachment: .Attachments.Add "C:\Path\File.pdf"
  • เพิ่ม CC/BCC: .CC = "manager@domain.com"
  • ใช้ Late Binding (CreateObject) ไม่ต้อง Add Reference Outlook Library