Excel VBA错误处理(简单但我无法弄清楚)

时间:2017-06-02 15:14:10

标签: excel vba excel-vba

好的,我试图将Error控件放在哪里,如果activecell行返回错误,它将占用行中的一个单元格,然后写入"错误"在上面。代码工作正常,直到我把On Error Control。我想我需要建议正确放置If else其中"错误"这个词会被放入。以下是代码。

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别名并将电子邮件发送给他/她。所以我试图把错误的别名放在&#34; xxxx&#34;上。问题是&#34;错误&#34;应该在activecell.cells(currow,13)上为&#34; xxxx&#34;使用Correct Alias记录行。那么如果错误的代码,我应该把代码放在哪里?

If Err.Number <> 0 Then

ActiveCell.Cells(CurRow, 13) = "Error"

End If

谢谢!

1 个答案:

答案 0 :(得分:1)

一般来说,总是尽量让你的代码尽可能简单,并消除无用的东西,只针对那些不起作用的东西。 你需要这样的东西:

Option Explicit

Public Sub Test()

    On Error Resume Next

    Debug.Print 5 / 0

    If Err.Number <> 0 Then
        Cells(1, 1) = Err.Description
    End If

    On Error GoTo 0

End Sub

然后从那里开始,您可以进一步构建代码。如果你需要一个循环并且{@ 1}}在@Mat&#39; Mug的评论中假设,它将如下所示:

Err.Clear

这会在5次迭代中产生3个错误,并将其描述写入活动的Excel工作表的A列。