Excel VBAerror handling没有完成它的工作

所以,我会先序说我还是VBA的新手。 我尽我所能并以此为荣。 我决定添加一些额外的function。 我想要的最后一个function是在发生错误时捕获特定的信息并将其显示在消息框中。

代码的作用是:

我有两个工作簿。 Wkbook1充满了大量的数据元素,Wkbook2是主列表。 该代码在wkbook1中search第一行,然后在Wkbook2中search该短语,然后在其左侧进行首字母缩写。 有时,有重复的元素,我的“DO LOOP”照顾。 我的问题是,不是所有的元素都出现在主列表中,我必须知道哪些不是。

我设置它,以便当出现错误消息,因为它无法find主列表中的元素,它去我的error handling程序,并将elment存储到我的消息variables,稍后将使用该消息框。

我testing了其他数据元素的工作簿,如果有0或1个元素没有find它的作品,但是当有超过1个元素在主列表中找不到,它给了我第二个元素没有find运行时错误91 。 我确信我的代码有很多批评,所以请放轻松一点。 这是我第一次使用数组。

码:

Option Explicit Sub M2_Name_Finder() Dim x As String Dim y As Integer Dim z As Integer Dim c As Integer Dim m As Integer Dim name As String Dim rngCopy As Range Dim numRows As Long Dim rAddress As String Dim found(50) As String Dim previous As String Dim missingFields As String Dim message As String name = "JJP" Windows("Wbook1").Activate Range("D3").Select Set rngCopy = ActiveCell.CurrentRegion numRows = rngCopy.Rows.Count For z = 1 To numRows Windows("Wkbook1").Activate Range("D3").Select ActiveCell.Offset(y, 0).Select x = ActiveCell.Value If x = vbNullString Or x = " " Then GoTo Done End If If x = previous Then GoTo Here End If previous = ActiveCell.Value Windows("Wkbook2").Activate Columns("D:D").Select On Error GoTo Missing: Selection.Find(what:=x, After:=ActiveCell, LookIn:=xlFormulas, LookAt _ :=xlWhole, SearchOrder:=xlByColumns, SearchDirection:=xlNext, MatchCase _ :=False, SearchFormat:=False).Activate found(c) = ActiveCell.Address rAddress = ActiveCell.Address If ActiveCell.Value <> Empty Or ActiveCell.Value <> 0 Then Do ActiveCell.Select ActiveCell.Offset(0, -3).Value = name c = c + 1 Cells.FindNext(After:=ActiveCell).Activate found(c) = ActiveCell.Address Loop While found(c) <> rAddress End If Here: c = 0 y = y + 1 Next z Missing: message = message & x m = m + 1 GoTo Here: Done: MsgBox "Not found: " & message & vbLf, vbInformation End Sub 

是的,我build议改变你的function有很多东西。 现在虽然我只是想谈谈你遇到的具体问题。 🙂

问题是,当你第一次inputerror handling,当你使用GoTo返回到正规的代码,你还没有离开error handling程序。 所以第二次你得到一个错误,它会引发error handling程序给用户。 您需要使用ResumeResume告诉系统你已经完成了处理错误并返回到常规的代码执行。

 Missing: message = message & x m = m + 1 Resume Here: 

我同意你已经包含了error handling,我没有批评mischab1的答案。

但是,我不赞成使用error handling来捕捉您所期望的错误; 它在那里的意外。 下面的代码好多了:

 Dim Rng As Range : : Set Rng = .... Find .... If Rng Is Nothing Then ' The Find has failed to locate the required string ' Include code for this situation Else ' The Find has found the required string ' Include code for this situation End If 

你仍然有意想不到的错误例行程序,但是这个代码不能用于查找失败的例行情况。

你问我们对你温柔,mischab1尊重你的愿望,但我会提出一个问题。

如果您在工作簿和工作表之间切换,并使用select和激活,则您的代码将不起作用,因为屏幕正在不断重新绘制。 您可以通过以下方式提高速度:

 Application.ScreenUpdating = False 

在开始和

 Application.ScreenUpdating = True 

最后。

切换工作簿时仍然会出现闪烁,但大部分屏幕活动都将被避免。

但是,最好不要使用SelectActivate 。 仔细观察一两个月的问题和答案。 许多(也许大多数)将不包含任何兴趣,但许多问题来自初学者,并且一些答案包括用于处理多个工作表和工作簿以及将数据从一个数据复制到另一个的优秀代码。 我相信学习这些答案会很快回报你的学习时间。

快乐编程!