Home » excel » excel – Sending e-mail with adresses in worksheet with VBA

excel – Sending e-mail with adresses in worksheet with VBA

Posted by: admin May 14, 2020 Leave a comment

Questions:

I have a sheet called “Test” where in column A is a list of e-mail adresses.
I want to send an e-mail to all adresses and use the following code

Sub EmailSend()

Dim objOutlook As Object
Dim objMail As Object
Dim i As Integer


Set objOutlook = CreateObject("Outlook.Application")
Set objMail = objOutlook.CreateItem(0)


For i = 1 To 10


With objMail
   .to = Sheets("Test").Range("A" & i).Value
   .Subject = "hi"
   .body = _ 
      "Hi " & Sheets("Test").Range("B" & i) & Sheets("links").Range("G" & 1)
   .send
End With
Next i


End Sub

Unfortunately the makro only sends an e-mail to the adress in A1 and then an error appears in the line .to = Sheets("Test").Range("A" & i).Value The error message says: element was moved or deleted.

Any idea what I did wrong?

How to&Answers:

My guess that the second line you are trying to send might have an error. Therefore, use the code below and check what it shows in the Immediate window.

UPDATE:
I’ve added the CreateItem line within the For loop and am resetting it for each mail. Possible it is the mail item that the error message is complaining about.

Sub EmailSend()

Dim objOutlook As Object
Dim objMail As Object
Dim i As Integer

Set objOutlook = CreateObject("Outlook.Application")

For i = 1 To 10
Set objMail = objOutlook.CreateItem(0)

With objMail
    Debug.Print Sheets("Test").Range("A" & i).Value
   .to = Sheets("Test").Range("A" & i).Value
   .Subject = "hi"
   .body = _
      "Hi " & Sheets("Test").Range("B" & i) & Sheets("links").Range("G" & 1)
   .display
   '.send
End With
Set objMail = Nothing

Next i

End Sub