2017-05-29 227 views
0

我尝试使用Outlook将电子邮件发送到Excel工作表中的column:A的每个电子邮件地址,并在主体中插入一个Word文档。我写了下面的代码,但它给了我运行时错误91.我使用的是Office 2013Vba运行时错误:91

Public Sub Create_Outlook_Email() 

Dim OutApp As Object, OutMail As Object, OutWordEditor As Object 
Dim WordDoc As Object 
Dim wordfile As String 
Dim rng As Range 
Dim row As Range 
Dim cell As Range 

'Create new Outlook email 
Set rng = Range("a2:a50") 
Set OutApp = CreateObject("Outlook.Application") 
Set OutMail = OutApp.CreateItem(0) 
Set OutWordEditor = OutMail.GetInspector.WordEditor 

For Each row In rng.Rows 
    For Each cell In row.Cells 

     With OutMail 
      .To = cell.Value 
      .Subject = "Your emails are moving on " & Range("e2").Value & "- don't get left behind  " 

      wordfile = Application.GetOpenFilename(Title:="Select MS Word file", MultiSelect:=False) 
      Set WordDoc = GetObject(wordfile) 
      WordDoc.Content.Copy 
      WordDoc.Close 
      OutWordEditor.Content.Paste 

      'See if Outlook is using Word to edit messages 

      .display 
      .send 
     End With 

     Set OutApp = Nothing 
     Set OutMail = Nothing 

     Set OutWordEditor = Nothing 
     Set WordDoc = Nothing 

    Next cell 
Next row 

End Sub 

回答

1

这将是更容易帮助,如果你提供的关于发生错误的行信息。例如,你有以下错误,这很可能是你的问题的根源:

Set OutWordEditor = Nothing 

你在循环内这样做,但你不设置下一次迭代OutWordEditor变量。因此,在第二次迭代中,在行OutWordEditor.Content.Paste处得到“对象未设置”。

的解决方案,我建议是,你将这些语句内:

Set OutMail = OutApp.CreateItem(0) 
Set OutWordEditor = OutMail.GetInspector.WordEditor 

此外,你不需要两个嵌套的循环,只有一个:

For Each row In rng.Rows 
For Each cell In row.Cells 
... 
Next 
Next 

与所有的以上,你的(单循环)变成这样:

For Each cell In rng.Cells 
    If Len(Trim(cell.Value)) = 0 Then Exit For ' <-- to stop at emty cell 
    Set OutMail = OutApp.CreateItem(0) 
    Set OutWordEditor = OutMail.GetInspector.WordEditor 
    ... 'Rest of the loop 
Next 
+0

@ YowE3K IIRC我们曾经讨论过这个:)这种打开word或excel文件的方式也是正确的;在注册表中找到适当的应用程序。 –

+0

不 - 不和我讨论这个问题。 (无论如何我都记得**)但我会相信你。 – YowE3K

+0

@ YowE3K这可能与你不一样,我不记得确切,但我很确定那是在我们初期彼此“见面”:P –