我想比较一下vba中某些单元格的值,但是如果找到N / A,代码会给我运行时错误,所以建议我将值与“#N / A”进行比较的代码

时间:2017-10-12 07:24:30

标签: excel vba excel-vba if-statement

如果我的单元格值不是#N/A,下面的代码工作正常,但我想将我的值与#N/A进行比较,那么请您帮我改变下面给出的代码:< / p>

enter code here
Lastrow = ws1.Cells(Rows.Count, "B").End(xlUp).Row
For i = 2 To Lastrow

If Cells(i, "AO").Value = "X" And Cells(i, "AP").Value = "X" Then
Cells(i, "N").Value = Cells(i, "M").Value * (-1)
Cells(i, "AA").Value = Cells(i, "M").Value
Cells(i, "AX").Value = "some content"
End If
Next i

2 个答案:

答案 0 :(得分:2)

这是如何看待两个单元格是否等于#NA。在你的支票中构建逻辑:

Public Sub TestMe()        
    If (Range("A1") = CVErr(xlErrNA)) And (Range("B1") = CVErr(xlErrNA)) Then
        'some logic
    End If        
End Sub

答案 1 :(得分:1)

您可以考虑添加另一个“IF..End If”来验证您测试条件的单元格是否包含错误值。

示例代码如下所示:

    Sub HandleErrorCells()
    Dim ws1 As Worksheet
    Set ws1 = ThisWorkbook.Sheets(1)
    Lastrow = ws1.Cells(Rows.Count, "B").End(xlUp).Row
    For i = 2 To Lastrow
        If Application.WorksheetFunction.IsError(Cells(i, "AO").Value) Or Application.WorksheetFunction.IsError(Cells(i, "AP").Value) Then
            Cells(i, "AX").Value = "Column AO or AP has error cell"
        Else
            If Cells(i, "AO").Value = "X" And Cells(i, "AP").Value = "X" Then
                If IsNumeric(Cells(i, "M").Value) Then
                    Cells(i, "N").Value = Cells(i, "M").Value * (-1)
                    Cells(i, "AA").Value = Cells(i, "M").Value
                    Cells(i, "AX").Value = "some content"
                Else
                    Cells(i, "AX").Value = "Column M has non numeric data"
                End If
            End If
        End If
    Next i
    End Sub