如何使字符串接受 Excel 错误 - 运行时错误 13 - 不匹配

How to make a string accept an Excel error- runtime error 13- mismatch

我正在尝试格式化下载的数据,然后插入 SQL。数据的性质是这样的,会出现诸如#NAME?、#N/A Invalid Field 等错误。我有一个数据类型为字符串的变量,每次 for 循环都会获取新单元格的值运行。当循环命中一个有错误的数据点时发生不匹配错误,循环崩溃(发现我的消息装箱循环)。

为什么字符串不能接受错误作为字符串的值?我已经看到关于此的 post 并且推荐的答案是使用 If IsError 但我需要错误的“#N/A”部分来识别错误已经发生,而不是跳过该行。任何建议将不胜感激!谢谢 :) 代码摘录如下:

'Insert static fields
Dim field As String

        code = "'" & tbl.DataBodyRange(i, 1) & "'"
        For j = 2 To 48

            MsgBox (tbl.DataBodyRange(i, j))
            field = tbl.DataBodyRange(i, j).Value
            'Recursively going through each cell

            If InStr(field, "#N") <> 0 Then
                field = "NULL "
                k = 1

它首先命中消息框的错误,消息框会显示不匹配的错误。

解决该问题的一种方法是使用 VARIANT 数据类型来处理错误。

如您所见,STRING 变量不能保存错误值,而 VARIANT 可以。然后,您可以使用以下代码:

IF ISERROR(field) THEN
   field = NULL  
   K=1  
END IF  

VARIANT 也可以包含 NULL 值。

编辑:

I have seen a post about this and the recommended answer was to use If IsError but I need the '#N/A' part of the error as to identify that one has occured, rather than skip the row.

ISERROR 部分标识发生了错误。这行代码本身不会跳过该行;它使您有机会对该行执行其他操作,例如将错误值替换为 NULL 值或其他一些必需的值。