As a business analyst, I need to repeatedly use cost and revenue data points to create different variants of a margin result.
I am trying to come up with a reusable piece of code that I can use and share so that everyone in my team can create their own margin analysis in power query with a few simple clicks.
Once I know how to do this, I can use the same logic on a plethora of other applications, so I'm looking forward to everyione's ideas!
I tried to write a custom function in Power Query M that would take two columns and return the results in more than one column.
The following piece of code does not work. It throws an error saying it expected an EoF Token in line 6:
(Cost as number, Revenue as number) =>
let
margin_absolute = Revenue - Cost,
margin_relative = Cost / Revenue
in
margin_absolute
in
margin_relative
Maybe I'm using the wrong approach?
I was able to make it work thanks to the below Chat GPT answer. I successfully tested the code.
"It looks like there are a couple of issues with your Power Query M code. The primary issue is with the structure of your
let...inexpression. You've closed thelet...inblock prematurely and attempted to return two values directly, which is not supported in the way you've structured it. Power Query M functions can only return a single value, but this value can be a record or a table, which can effectively contain multiple values (or columns).Here's how you can modify your function to return both
margin_absoluteandmargin_relativeas a record:In this revised version:
CostandRevenueas inputs.margin_absoluteandmargin_relative.Margin_AbsoluteandMargin_Relative.margin_relativecalculation.To use this function in your Power Query editor:
Create the Function: Copy the revised function into a new blank query to create the function.
Invoke the Function: To use this function, you'll need to call it for each row of your table. Suppose your table has columns named
CostandRevenue. You can add a custom column to call this function:Expand the Record: After adding the custom column, you'll have a column of records. You can expand this to create two new columns,
Margin_AbsoluteandMargin_Relative, by using the "Expand Column" feature in the Power Query editor.This approach allows you to encapsulate the margin calculations in a single function, which can be reused across multiple queries or shared with your team."