[Solved] Auto-Calculate Gross Profit

Tsd5562

New member
I want to use VBA to automatically add a new column "Gross Profit" (Revenue – COGS) and populate it for all rows. How do I insert the column and calculate?
QuarterProduct LineRevenue (USD)Cost of Goods Sold (COGS)Operating ExpensesNet Income
Q1-2023Alpha120,00070,00020,00030,000
Q2-2023Alpha135,00075,00022,00038,000
Q3-2023Alpha150,00078,00024,00048,000
Q4-2023Alpha160,00080,00025,00055,000
Q1-2024Beta90,00045,00018,00027,000
Q2-2024Beta100,00050,00019,00031,000
Q3-2024Beta110,00052,00020,00038,000
Q4-2024Beta120,00055,00021,00044,000
 
Hello Tsd5562,

You can use the following VBA code to automatically insert a new column labeled "Gross Profit" to the right of "Revenue (USD)" and calculate the values as Revenue – COGS for each row:

Code:
Sub AddGrossProfitColumn()
    Dim ws As Worksheet
    Dim lastRow As Long
    Dim i As Long

    Set ws = ActiveSheet ' Or specify your sheet: Worksheets("Sheet1")

    ' Find the column index for "Revenue (USD)" and "Cost of Goods Sold (COGS)"
    Dim revenueCol As Long, cogsCol As Long, insertCol As Long
    revenueCol = ws.Rows(1).Find("Revenue (USD)").Column
    cogsCol = ws.Rows(1).Find("Cost of Goods Sold (COGS)").Column

    ' Insert new column to the right of Revenue
    insertCol = revenueCol + 1
    ws.Columns(insertCol).Insert Shift:=xlToRight
    ws.Cells(1, insertCol).Value = "Gross Profit"

    ' Get last row with data
    lastRow = ws.Cells(ws.Rows.Count, revenueCol).End(xlUp).Row

    ' Loop through each row to calculate Gross Profit
    For i = 2 To lastRow
        ws.Cells(i, insertCol).Formula = "=" & ws.Cells(i, revenueCol).Address & "-" & ws.Cells(i, cogsCol).Address
    Next i

    MsgBox "Gross Profit column added successfully!"
End Sub
This code will:
  • Insert a "Gross Profit" column next to Revenue.
  • Calculate each row using =Revenue - COGS.
  • Work for dynamic ranges.
 

Online statistics

Members online
0
Guests online
34
Total visitors
34

Forum statistics

Threads
416
Messages
1,845
Members
901
Latest member
JORGE W: ROSERO
Back
Top