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

Workdays for a market open Mon, Wed, Friday?
Yes! Use "0101011" for the weekend argument in NETWORKDAYS.INTL or WORKDAY.INTL. The 7 digits start on Monday. 1 means it is a weekend.
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,223,892
Messages
6,175,236
Members
452,621
Latest member
Laura_PinksBTHFT

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