Vba for循环中的类型不匹配,包括工作表单元格值的测试
我在VBA宏中收到类型不匹配错误。以下是我的代码的基本部分:Vba for循环中的类型不匹配,包括工作表单元格值的测试,vba,excel,type-mismatch,Vba,Excel,Type Mismatch,我在VBA宏中收到类型不匹配错误。以下是我的代码的基本部分: Public Function CalculateSum(codes As Collection, ws As Worksheet) As Double On Error GoTo ErrorHandler If ws Is Nothing Then MsgBox ("Worksheet is necessery") Exit Function End If Dim balanceColumnIndex, co
Public Function CalculateSum(codes As Collection, ws As Worksheet) As Double
On Error GoTo ErrorHandler
If ws Is Nothing Then
MsgBox ("Worksheet is necessery")
Exit Function
End If
Dim balanceColumnIndex, codesCulumnIndex As Integer
Dim searchStartRow, searchEndRow As Integer
balanceColumnIndex = 17
codesColumnIndex = 4
searchStartRow = 7
searchEndRow = ws.Cells(ws.Rows.Count, codesColumnIndex).End(xlUp).Row
Dim result As Double
result = 0#
For counter = searchStartRow To searchEndRow
If Len(ws.Cells(counter, codesColumnIndex)) > 0 And Len(ws.Cells(counter, balanceColumnIndex)) > 0 And _
IsNumeric(ws.Cells(counter, codesColumnIndex).Value) And IsNumeric(ws.Cells(counter, balanceColumnIndex).Value) Then
If Contains(codes, CLng(ws.Cells(counter, codesColumnIndex).Value)) Then
result = result + ws.Cells(counter, balanceColumnIndex).Value
''' ^^^ This line throws a type-mismatch error
End If
End If
Next counter
CalculateSum = result
ErrorHandler:
Debug.Print ("counter: " & counter & "\ncode: " & ws.Cells(counter, codesColumnIndex).Value & "\namount: " & ws.Cells(counter, balanceColumnIndex).Value)
End Function
现在发生的情况是,在当前行余额添加到结果的行上发生类型不匹配错误,即使:
- searchEndRow等于129,而计数器不知何故等于130
- 当前地址下的单元格是空的,但不知何故它们通过了长度和数值测试(我在这里停止调试,
IsNumeric(ws.cells(counter,codescolumnidex).Value)
返回true
现在我很困惑,我不知道该怎么办。请帮助。正如评论员所指出的,单元格(…).Value
是一个变量
。这意味着运算符可能不会按预期的方式应用于Value
。对于使用Len
或其他字符串操作的测试,请明确转换为字符串。例如,请尝试Len(ws.Cells(…)
,而不是Len(ws.Cells(…)
)
。这样你就会知道Len
正在给你你期望的结果
类似地,在添加到result
的位置,使用result=result+CDbl(ws.Cells(…).Value)
确保将两个值一起添加
要回答您关于不同计算机上发生不同错误的问题,我最常遇到的是,这是所讨论的特定数据。正如一位评论员指出的,Empty
确实是数字,因为它隐式转换为0
!因此,是数字(Empty)
是True
。使用CStr
可以防止代码中出现这种情况,因为IsNumeric(CStr(Empty))=IsNumeric(“”=False
。使用IsNumeric(CStr(…)
可以防止您尝试添加0++“
,这是一种类型不匹配。因此,可能用户的测试数据中没有空单元格,这就是问题的原因。这不是唯一的可能性,只是我遇到最多的可能性。在for…to…
中使用的变量将始终是循环后的限制+1。这是正常的。Cells.Value代码>返回一个变量。如果它是空的,那么它可以被转换为数字(0),因此是数字。同样,这是正常的。你确定该值实际上是空的吗?可能是零,并且你已经设置为False
?你确定Len
返回>0吗?(你只说你检查了IsNumeric
部分)两种想法:(1)不要使用Len(单元格(…)
,而应尝试Len(CStr(单元格(…).Value))
,以确保您正在检查字符串。(2)请记住,VBA没有短路评估功能,因此无论Len
测试如何,您的If
语句中的测试都是数字的。我不认为这是您的问题,但它可能会让您感到困惑。我使用嵌套的If
语句手动执行希望VBA在或者我;)。