获取类型不匹配错误

时间:2013-08-12 17:06:07

标签: excel vba excel-vba

此VBA代码验证计算的单元格。如果该值超过$ 500.00或具有#N / A,那么它应该为整行和粗体字体着色。

但我一直收到Type Mismatch错误:

Dim lngCounter As Long
Dim Lastrow As Long

Lastrow = ActiveSheet.Range("A65536").End(xlUp).Row

For lngCounter = 3 To Lastrow
    With Cells(lngCounter, "J")
        If .Value >= 500 Or IsError(Cells) Then
            Cells(lngCounter, "I").Interior.ColorIndex = 44
            Cells(lngCounter, "J").Interior.ColorIndex = 44
            Rows(lngCounter).Font.Bold = True

        Else

        End If
    End With
Next lngCounter

3 个答案:

答案 0 :(得分:2)

这一行可能会引发错误:

If .Value >= 500 Or IsError(Cells) Then

该行有两个错误。 Cells在您的代码中没有任何内容。你需要像Cells(lngCounter, "J")

此外,如果该单元格包含错误值,则在尝试评估该法规的前半部分时会出现Mismatch错误,因为#N/A#DIV0!等不是数值,因此存在与>=等数字运算符一起使用时类型不匹配。

使用更多变量,并稍微调整一下代码。试试这个(未经测试):

Sub Test()
Dim lngCounter As Long
Dim Lastrow As Long
Dim myCell as Range

Lastrow = ActiveSheet.Range("A65536").End(xlUp).Row

For lngCounter = 3 To Lastrow
    Set myCell = Cells(lngCounter, "J")
    With myCell
        If IsError(.Value) Then
            FormatThis myCell
        ElseIf .Value >= 500 Then
            FormatThis myCell
        End If
    End With
Next lngCounter
End Sub
Sub FormatThis(cl as Range)
    'receives a cell in column J, use the OFFSET and RESIZE methods
    ' to return a range of cells in columns I & J to format color.
    cl.Offset(0,-1).Resize(1,2).Interior.ColorIndex = 44
    Rows(cl.Row).Font.Bold = True
End Sub

答案 1 :(得分:1)

它必须是VBA吗?您可以将此条件格式公式应用于第3行:65536

=AND(OR($J3>=500,ISNA($J3)),$J3<>"")

答案 2 :(得分:1)

您必须始终测试错误第一个

Sub dural()
For Each r In Selection
    If IsError(r.Value) Then
        MsgBox r.Text
    Else
        If r.Value > 100 Then
            MsgBox r.Value
        End If
    End If
Next r
End Sub