for循环中的types不匹配,包括工作表单元格值的testing

我在我的VBAmacros中收到types不匹配错误。 这是我的代码的重要部分:

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 

现在会发生什么types不匹配的错误发生在添加当前行平衡的行上,即使:

  • searchEndRow等于129,不知何故计数器等于130
  • 在当前地址下的单元格是空的,但他们通过testing的长度和数值(我停止debugging在这一点上, IsNumeric(ws.Cells(counter, codesColumnIndex).Value)返回true

现在我只是困惑,我不知道该怎么做。 请帮忙。

正如评论者所指出的, Cells(...).Value是一个Variant 。 这意味着运营商可能不会按照您期望的方式申请。 对于使用Len或其他string操作的testing,请明确转换为string。 例如,而不是Len(ws.Cells(...)) ,请尝试Len(CStr(ws.Cells(...).Value)) 。 这样你就会知道Len给你的结果是你期望的。

类似的,在你添加result ,使用result = result + CDbl(ws.Cells(...).Value)来确保你将Double值加在一起。

为了回答你关于在不同计算机上发生的错误的问题,我经常遇到的问题是它是具体的数据。 正如其中一位评论者指出的那样, Empty确实是数字,因为它隐含地转换为0 ! 因此, IsNumeric(Empty)True 。 因为IsNumeric(CStr(Empty)) = IsNumeric("") = False ,因此在您的代码中使用CStr警卫。 使用IsNumeric(CStr(...))可以防止您尝试添加0# + "" ,这是一种types不匹配。 所以也许用户有一个空的单元格,你没有在你的testing数据,这是造成这个问题。 这不是唯一的可能性,就是我最经常遇到的一个。