繁体   English   中英

VBA运行时错误:91

[英]Vba runtime error: 91

我正在尝试使用Outlook将电子邮件发送到Excel工作表中的column:A每个电子邮件地址,并将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 

您正在循环内执行此操作,但随后在下一次迭代中不要设置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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM