由于不确定原因,VBA 代码显示错误 2042

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13761586/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-08 14:33:40  来源:igfitidea点击:

VBA code showing error 2042 for reason unsure

excelvba

提问by Jonathan Raul Tapia Lopez

I have a variable filawith a full line with Excel's values

我有一个fila带有 Excel 值的整行变量

The problem is when in Excel I have #N/A, VBA takes that value like Error 2042.

问题是当我在 Excel 中时#N/A,VBA 会像Error 2042.

I cannot assign that value to valorandproduce an error. Until this point everything is ok, now I am trying to define a On Error Gototo go to the next iteration in the Forloop, but I do notknow why VBA doesn't handle the error.

我无法将该值分配给valor产生错误。到目前为止一切正常,现在我试图定义一个On Error Goto去循环中的下一次迭代For,但我知道为什么 VBA 不处理错误。

Do While Not IsEmpty(ActiveCell)

    txt = ActiveCell.Value2
    cell = ActiveCell.Offset(0, 1).Value2       
    fila = Range("C20:F20")

    For j = 1 To UBound(fila, 2)
        On Error GoTo Siguiente
        If Not IsEmpty(fila(1, j)) Then            
            valor = fila(1, j)
            cmd = Cells(1, j + 2).Value2
            devolver = function1(cmd, txt, cell, valor)
            arrayDevolver(p) = devolver
            p = p + 1                
        End If
Siguiente:
    Next
Loop 

回答by brettdj

This is not a VBA error - so error handling won't catch it. To detect this issue use IsErrorbefore writing to your array

这不是 VBA 错误 - 因此错误处理不会捕获它。要IsError在写入阵列之前检测此问题,请使用

The simple code below handles the Error 2042problem with this test

下面的简单代码处理此测试的错误 2042问题

Sub Test()
    Dim varIn As Variant
    [a1].FormulaR1C1 = "=NA()"
    If IsError([a1].Value2) Then
        varIn = "skip record"
    Else
        varIn = [a1].Value2
    End If
End Sub