我想創建一個簡單的公式來計算某一行的凈變化,并將其列印在同一行(H 列)。但是我插入公式的內容將取決于每行 A 列的值。
這是我嘗試過的代碼:
Sub totalPnL()
Dim LR As Long
LR = Range("D" & Rows.Count).End(xlUp).Row
If Range("A2:A" & LR).Value = "WIN" Then
Range("H2:H" & LR).Formula = "=ABS(D2-F2)*G2"
ElseIf Range("A2:A" & LR).Value = "LOSS" Then
Range("H2:H" & LR).Formula = "=-ABS(D2-E2)*G2"
End If
Range("T2") = Application.WorksheetFunction.Sum(Range("H:H"))
End Sub
我覺得 If 陳述句有問題,但我不知道如何編輯它
感謝所有的幫助
uj5u.com熱心網友回復:
正如評論中所寫的那樣,公式會更容易和更快,但如果你想讓你的代碼“修復”,那么下面的代碼就可以了。
Sub totalPnL()
Dim LR As Long, i As Long
LR = Range("D" & Rows.Count).End(xlUp).Row
' the original statement
' Range("A2:A" & LR).Value = "WIN"
' cannot work as Range("A2:A" & LR) will be an array in case LR > 2
' in this case you have to loop
' AGAIN: usage of a formula will be better
For i = 2 To LR
If Range("A" & i).Value = "WIN" Then
Range("H" & i).FormulaR1C1 = "=ABS(RC[-4]-RC[-2])*RC[-1]"
ElseIf Range("A" & i).Value = "LOSS" Then
Range("H" & i).FormulaR1C1 = "=ABS(RC[-4]-RC[-2])*RC[-1]"
End If
Next i
Range("T2") = Application.WorksheetFunction.Sum(Range("H:H"))
End Sub
為了使代碼更易于閱讀,您可以使用Select陳述句
For i = 2 To LR
Select Case Range("A" & i).Value
Case "WIN"
Range("H" & i).FormulaR1C1 = "=ABS(RC[-4]-RC[-2])*RC[-1]"
Case "LOSS"
Range("H" & i).FormulaR1C1 = "=ABS(RC[-4]-RC[-2])*RC[-1]"
End Select
Next i
您可以使用的另一個公式是
=IF(A2="WIN";1;(IF(A2="LOSS";-1)))*ABS(D2-F2)*G2
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/512669.html
