我的错误处理程序只工作一次,我不明白为什么

My error handler works just once and I don't understand why

我正在尝试借助命名范围翻译一些 Excel 文件。我需要知道哪些文本尚未定义,然后将其添加到名称数据库中。为此,我使用 VLOOKUP 将单元格的实际值与数据库中的值进行比较。我也不需要翻译数字、公式或任何不是字符串的东西。

我发现将未定义名称添加到数据库的唯一方法是在 VLOOKUP 遇到错误时使用错误处理程序。问题是这个错误处理程序只工作一次,我不明白为什么。我读过你必须使用 Resume 才能做到这一点,我已经使用了它,但它不起作用。

在此先感谢您的帮助,对于语法错误,我们深表歉意。

这是我的代码。

Sub translation()
Dim cell, cell1, cell2 As Range, search_value As String, i As Integer
i = 3
For Each cell In Hoja65.Range("D3:D10") 'Range to look up for words.
        If IsEmpty(cell) = False And IsError(cell) = False And IsNumeric(cell) = False Then ' Enter code if the cell is not empty and is not an error
                ' Check if read value is equal to any exception listed in Hoja65.Range("B3:E20")
                For Each cell1 In Hoja65.Range("E3:E10")
                        ' Check if read value is a formula beginning with "=", "+" or "-" or contains an hyperlink.
                        If cell1 = cell Or InStr(1, cell.FormulaLocal, "=", vbTextCompare) = 1 Or InStr(1, cell.FormulaLocal, "+", vbTextCompare) = 1 Or InStr(1, cell.FormulaLocal, "-", vbTextCompare) = 1 Or InStr(1, cell.Value, "http", vbTextCompare) <> 0 Then
                                GoTo continue
                        End If
                Next cell1
                ' If read value is not equal to exception
                On Error GoTo handler
                search_value = Application.WorksheetFunction.VLookup(cell.Value, Hoja64.Range("F9:G550"), 2, False) ' Range where the names are defined.
                cell.Value = "=" & search_value 'Change read to defined name.
        End If
continue:
Next cell
MsgBox "Execution finished"
Exit Sub ' VERY IMPORTANT: This line must ALWAYS precede any error handler in order to avoid an infinite loop.
handler: ' Executes only if VLOOKUP doesn't find a match
        With Hoja65
                For Each cell2 In .Range(.Cells(3, 3), .Cells(i, 3))
                If cell2 = cell Then
                        GoTo continue
                Else
                        .Cells(i, 2) = cell.Address ' Save address of unsaved name.
                        .Cells(i, 3) = cell.Value ' Save value of unsaved name.
                End If
                i = i + 1
                Next cell2
        End With
        Resume continue
'ActiveSheet.Shapes.Range(Array("Rounded Rectangle 2")).Select
'Selection.Formula = "=title270"
End Sub
            If cell2 = cell Then
                    GoTo continue

这就是原因。您不会 GoTo-跳转 in/out 错误处理子程序; GoTo 没有 "reset" 错误状态,因此您使用 Err.Number <> 0 重新进入 "happy path",即您仍处于错误状态。

GoTo 替换为 Resume,您应该回到正轨。

            If cell2 = cell Then
                    Resume continue