[英]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.