VBA运行时错误:91

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

 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 

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

 Set OutWordEditor = Nothing 

你在循环里面做这个,但是你不要在下一次迭代中设置OutWordEditorvariables。 因此,在第二次迭代中,在OutWordEditor.Content.Paste这一行OutWordEditor.Content.Paste得到“未设置对象”。

我build议的解决scheme是将这些语句移到循环中

 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