好吧,我試圖把一個錯誤控制,如果activecell行返回錯誤,它將佔用行中的單元格,並只寫「錯誤「 在上面。代碼工作正常,直到我把On Error Control。我想我需要告訴If If的錯誤詞將被放入的正確位置。以下是代碼。Excel VBA錯誤處理(簡單,但我不明白)
Private Sub CommandButton1_Click()
Dim outlookapp As Outlook.Application
Dim outlookmail As Outlook.MailItem
Dim myusername As String
Dim LastRow As Long, CurRow As Long, DestRow As Long, DestLast As Long
Dim checkstatus As String
Dim ws1 As Worksheet, ws2 As Worksheet
Set ws1 = Sheets("Sheet1")
LastRow = ws1.Range("A" & Rows.Count).End(xlUp).Row
On Error Resume Next
For CurRow = 2 To LastRow
myusername = Environ("Username")
Set outlookapp = New Outlook.Application
Set outlookmail = outlookapp.CreateItemFromTemplate("C:\Users\" & myusername & "\AppData\Roaming\Microsoft\Templates\testtemplate.oft")
With outlookmail
.SentOnBehalfOfName = "SharedMailbox"
.To = ActiveCell.Cells(CurRow, 6)
.Subject = Replace(outlookmail.Subject, "xProjID", ActiveCell.Cells(CurRow, 1))
.Subject = Replace(outlookmail.Subject, "xProjName", ActiveCell.Cells(CurRow, 2))
.Subject = Replace(outlookmail.Subject, "xVert", ActiveCell.Cells(CurRow, 5))
.HTMLBody = Replace(outlookmail.HTMLBody, "xXName", ActiveCell.Cells(CurRow, 2))
.HTMLBody = Replace(outlookmail.HTMLBody, "xProjID", ActiveCell.Cells(CurRow, 1))
.HTMLBody = Replace(outlookmail.HTMLBody, "xStat", ActiveCell.Cells(CurRow, 10))
.HTMLBody = Replace(outlookmail.HTMLBody, "xManID", ActiveCell.Cells(CurRow, 6))
.HTMLBody = Replace(outlookmail.HTMLBody, "xName", ActiveCell.Cells(CurRow, 7))
End With
ActiveCell.Cells(CurRow, 11) = "Yes"
ActiveCell.Cells(CurRow, 12) = DateTime.Now
If Err.Number <> 0 Then
ActiveCell.Cells(CurRow, 13) = "Error"
End If
outlookmail.Send
Next CurRow
MsgBox "Mass Mailer Complete"
End Sub
因此,它會獲取特定用戶的Outlook別名並將電子郵件發送給他/她。所以我試圖把錯誤的別名,如「xxxx」。事情是應該在activecell.cells(currow,13)中的「錯誤」一詞,對於具有「xxxx」的行使用正確的別名記錄行。那麼我應該在哪裏把代碼放在代碼中?
If Err.Number <> 0 Then
ActiveCell.Cells(CurRow, 13) = "Error"
End If
謝謝!
爲什麼'ActiveCell.Cells'而不是'ws1.Cells'? –
Doc.SO上的[VBA錯誤處理](https://stackoverflow.com/documentation/vba/3211/error-handling#t=201706021519538153681)應該包含您需要知道的所有內容。用正確的錯誤處理替換'錯誤恢復下一個'。也就是說,你並沒有清除迭代之間的錯誤狀態('Err.Clear') - 這可能是你的問題所在。 –
除了@Mat'sMug建議的內容,如果我理解了你的帖子,我想你也可能想看看[解析收件人](https://msdn.microsoft.com/en-us/library/office/outlook862796.aspx)在Outlook VBA中的方法。如果聯繫已解決,您可以發送電子郵件,如果沒有,您可以將錯誤放入單元格中。通過這種方式,您無需任何錯誤陷印。正如所寫的,代碼不會在Excel端產生任何錯誤,這就是爲什麼你沒有得到任何錯誤。 –