【发布时间】:2021-05-13 17:52:52
【问题描述】:
多年来,我一直在使用修改后的匹配功能,效果很好。但是突然我无缘无故地收到运行时错误13。该函数在实际过程中调用了两次,才弹出错误。第一次一切正常,第二次出现错误。代码如下:
Public Function xMatch(ByRef Direction_Range As Range, ByVal Find_Value_Or_String, Occ_Number As Integer, Row_True_Or_Column_False As Boolean, RelativePosition_True_Or_AbsolutePosition_False As Boolean) As Integer
Dim xMTcell
toolVar1 = 0
xMatch = 0
occurrencesCount = 0
If RelativePosition_True_Or_AbsolutePosition_False = True Then
If Row_True_Or_Column_False = True Then
toolVar1 = Range(Split(Direction_Range.Address, ":")(0)).Row - 1
Else
toolVar1 = Range(Split(Direction_Range.Address, ":")(0)).Column - 1
End If
End If
For Each xMTcell In Direction_Range
If xMTcell.Value = Find_Value_Or_String Then
occurrencesCount = occurrencesCount + 1
If occurrencesCount = Occ_Number Then
If Row_True_Or_Column_False = True Then
xMatch = xMTcell.Row - toolVar1
Else
xMatch = xMTcell.Column - toolVar1
End If
Exit For
End If
End If
Next xMTcell
End Function
toolVar1 和occurrencesCount 在模块中声明。该函数可以在任何范围(Direction_Range)中搜索并找到值(Find_Value_Or_String)。与常规匹配函数相反,您可以决定 (Occ_Number) 如果该范围内有多个查找,则哪个查找将是您需要的查找。此外,您可以决定是否需要该查找的行或列,以及是否需要该行/列绝对(与工作表相比的位置)或相对(与 Direction_Range 相比的位置)。
错误出现在这一行:
If xMTcell.Value = Find_Value_Or_String Then
由于 xMTcell 是 Direction_Range 的一部分,我检查了 Range,它显然是正确的,加上它是一个范围,仅此而已。我还检查了值,它是他正在寻找的字符串,可以在该范围内手动找到。我不明白为什么它在流程的其他阶段使用完全相同类型的 Direction_Range 和 Find_Value_Or_String 可以正常工作,但突然就不行了。我已经尝试将 xMTcell 声明为 Range,但没有任何区别。
谁有想法?
问候 卡尔
根据 cmets 我做了以下检查:
Debug.Print VarType(Direction_Range)
Debug.Print Direction_Range.Address
Debug.Print VarType(xMTcell.Value)
Debug.Print VarType(Find_Value_Or_String)
Debug.Print xMTcell.Address
对于我得到的非窃听过程
8204
$A$4:$N$4
8
8
$B$4
对于窃听过程
8204
$A$5:$A$16
8204
8
$A$5:$A$16
所以它的范围有问题,为什么它的行为不同?
【问题讨论】:
-
出错时
xMTcell和Find_Value_Or_String的值是多少? -
在您的工作表上查找
#N/A或#VALUE!或#REF!错误。这些值具有Variant/Error数据类型,每次您尝试将它们与Variant/Error以外的任何内容进行比较时,都会引发类型不匹配。使用IsError函数测试变体的子类型,并在子类型为Error时返回True。 -
@BigBen
xMTcell在鼠标悬停时不显示任何值(与范围一样),Find_Value_Or_String显示字符串 -
您可以使用
Debug.Print。检查即时窗口中的输出(使用 Ctrl+G 调出)。也很有用:Debug.Print VarType(xMTcell.Value)、Debug.Print VarType(Find_Value_Or_String)。 -
8204意味着xMTcell是一个多单元格范围,而不是单个单元格。也可以使用Debug.Print xMTcell.Address进行验证。很可能您将Row或Column传递给Direction_Range。可能通过使用For Each xMTcell In Direction_Range.Cells解决。
标签: excel vba runtime-error match type-mismatch