获得细胞的差异

时间:2016-02-29 10:13:08

标签: excel vba excel-vba

任何人都知道如何区分具有条件的两个细胞。我的问题是,如果Column W包含FAILED的值,那么我必须得到Column PColumn Q的差异,并将差异加到Column Z。然后我必须这样做,直到最后一行有Column W中的数据。到目前为止我有这个代码:

If ws.Range("W3") = "FAILED" Then
    ws.Range("Z3") = ws.Range("P3") - ws.Range("Q3")
Else
    ws.Range("Z3") = ""
End If

ws.Range("Z3").Copy
ws.Range("Z3:Z" & GetLastRow(ws)).PasteSpecial xlPasteValues

有任何帮助吗?谢谢!

2 个答案:

答案 0 :(得分:0)

如果您真的想在VBA中执行此操作,则可以将代码更改为:

Sub calc()
    Dim ws As Object
    Set ws = ActiveSheet
    Row = 3
    Do
        If WorksheetFunction.CountA(ActiveSheet.Rows(Row)) = 0 Then Exit Do 'exit loop if row is empy
        If ws.Cells(Row, 23).Text = "FAILED" Then
            ws.Cells(Row, 26) = ws.Cells(Row, 16) - ws.Cells(Row, 17)
        Else
            ws.Cells(Row, 26) = ""
        End If
        Row = Row + 1
    Loop
End Sub

注意我赞成对列的数字引用。

但除非你打算升级到更复杂的案件,否则我会在Z栏上坚持使用公式:

=IF(W1="FAILED",P1-Q1,"")

答案 1 :(得分:0)

Sub GetDiff()
Dim Ws As Worksheet, lRw As Long

Set Ws = ActiveSheet

Application.ScreenUpdating = False

With Ws
    lRw = .Range("W" & Rows.Count).End(xlUp).Row
    With .Range("Z3:Z" & lRw)
        .Formula = "=IF(W3=""Failed"",SUM(P3)-SUM(Q3),0)"
        .Calculate
        DoEvents 'This will let the formula to calculate before converting it to values
        .Value = .Value
    End With
End With

Application.ScreenUpdating = True

End Sub