Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.1k views
in Technique[技术] by (71.8m points)

excel - server execution failed -VBA outlook email automation failed

i'm new to VBA and im trying to write a macro that automates mail sending from mail list (using outlook15), and attaching a pdf file to them. i wrote the following script, that loops thrugh 16 cells with mail addresses, and attaches pdf files ( via path).

for some reason i am getting the following message: "run time error '-2146959355(80080005)': server execution failed" . when i hit debug, the row : "Set outlookapp = CreateObject("Outlook.Application")" is being highlited.

any ideas how to solve it?


Sub SndEmail()
'define variables and their types'
Dim address As String
Dim subject As String
Dim message As String
Dim filename As String
Dim outlookapp As Object
Dim outlookmailitem As Object
Dim myAttachments As Object
Dim path As String
Dim lastrow As String
Dim attachment As String
'x will be row index we loop through'
Dim x As Integer

x = 61

Do While x < 77
        
    Set outlookapp = CreateObject("Outlook.Application")
    Set outlookmailitem = outlookapp.CreateItem(0)
    Set myAttachments = outlookmailitem.Attachments
    'taking the file path from cells in excel'
    path = sheet1.Cells(x, 4)
    address = sheet1.Cells(x, 3)
    subject = "hello world"
    attachment = path
        
        outlookmailitem.To = address
        outlookmailitem.CC = ""
        outlookmailitem.BCC = ""
        outlookmailitem.subject = subject
        'taking the body content from cell 56'
        outlookmailitem.Body = sheet1.Cells(56, 3)
                
        myAttachments.Add (attachment)
        outlookmailitem.Display
        outlookmailitem.Send
        
        address = ""
    x = x + 1
Loop
        
    Set outlookapp = Nothing
    Set outlookmailitem = Nothing


End Sub


'''
 
question from:https://stackoverflow.com/questions/65642597/server-execution-failed-vba-outlook-email-automation-failed

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You are creating new instances of these objects for each loop:

Set outlookapp = CreateObject("Outlook.Application")
Set outlookmailitem = outlookapp.CreateItem(0)
Set myAttachments = outlookmailitem.Attachments

If you are familiar with C/C++, Java etc. the Set in VBA equals new in C/C++/Java

So put these lines outside (before) the loop


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...