VBA: Calculating the value at every row, but formula changes depending on the value in one column

yijiyap

New Member
Joined
Oct 7, 2022
Messages
2
Office Version
  1. 2021
  2. 2019
  3. 2016
  4. 2013
Platform
  1. MacOS
I would like to create a simple formula to calculate the net change on a certain row, and print it in the same row (column H). But what I plug into the formula will depend on the value at each row's column A.

This is the code that I tried:

VBA Code:
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

I feel something is wrong with the If statement, but I'm not sure how to edit it

Thanks for all the help
 

Excel Facts

Can you sort left to right?
To sort left-to-right, use the Sort dialog box. Click Options. Choose "Sort left to right"
Welcome to the MrExcel board!

I am assuming that all the values in A2:A & LR are either "WIN" or "LOSS"
If that is the case, then try this code.

VBA Code:
Sub totalPnL_v2()
  Dim LR As Long
  
  LR = Range("D" & Rows.Count).End(xlUp).Row
  Range("H2:H" & LR).Formula = "=IF(A2=""WIN"",ABS(D2-F2)*G2,-ABS(D2-E2)*G2)"
End Sub
 
Upvote 0
Solution
Wow thanks for the well-wishes and the prompt answer :) I didn't think of that logic haha It worked like a charm! Cheers :)
 
Upvote 0
You're welcome. Thanks for the follow-up. :)
 
Upvote 0

Forum statistics

Threads
1,224,822
Messages
6,181,165
Members
453,021
Latest member
Justyna P

We've detected that you are using an adblocker.

We have a great community of people providing Excel help here, but the hosting costs are enormous. You can help keep this site running by allowing ads on MrExcel.com.
Allow Ads at MrExcel

Which adblocker are you using?

Disable AdBlock

Follow these easy steps to disable AdBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the icon in the browser’s toolbar.
2)Click on the "Pause on this site" option.
Go back

Disable AdBlock Plus

Follow these easy steps to disable AdBlock Plus

1)Click on the icon in the browser’s toolbar.
2)Click on the toggle to disable it for "mrexcel.com".
Go back

Disable uBlock Origin

Follow these easy steps to disable uBlock Origin

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back

Disable uBlock

Follow these easy steps to disable uBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back
Back
Top