【问题标题】:Vba runtime error: 91Vba 运行时错误:91
【发布时间】:2017-05-29 00:25:20
【问题描述】:

我正在尝试使用 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

【问题讨论】:

    标签: excel vba outlook ms-word runtime-error


    【解决方案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
    

    【讨论】:

    • @YowE3K IIRC 我们过去讨论过这个问题:) 这种打开word或excel文件的方式也是正确的;在注册表中找到相应的应用程序。
    • 不 - 没有与我讨论过。 (反正我不记得。)但我会相信你。
    • @YowE3K 那可能不是和你在一起的,我记不太清了,但我很确定那是在早期我们“相遇”的时候:P
    • 哦——看看那个(我刚试过)——我又学到了一些新东西!!!谢谢
    • 我不记得我昨天讨论的事情,所以肯定不会记得“早期”的事情:D
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多