User-defined DAX functions

The DAX statement language, which we use to add new reporting dimensions to the Semantic Model, whether they are measures or calculated columns, or we use it to create tables, has a large number of functions. However, sometimes users need to create their own functions, and recently they can do it in a simple way, most often through DAX query view.

User-defined functions are still new feature, and in order for them to work, you must first enable them in the Power BI Options, Preview Features section.

We imported into the Model and linked two tables there: Artikli (Items) and Transakcije(Transactions). There are also two measures that calculate Prihodi (Revenues) and Troskovi (COGS) based on sales transactions.

We will create user-defined functions within DAX query view. The syntax of the new function looks like this:

FUNCTION <Name> = (<ParameterName>: <ParameterType>, … ) => <Function Body>

How this works we will see with an example. Let’s create a function by which we calculate the Gross Margin. First, we’ll enter the DEFINE command, and then enter the new function:

DEFINE

FUNCTION BM = (pr: NUMERIC, tr: NUMERIC) => pr – tr

Once you’ve created a function, the first thing you need to do  is click on the Update model with changes button. In this way, Intellisense will be able to recognize the newly created function. Then, in the Transactions table, we make a new measure:

Gross Margin = BM ([Revenue],[Expenses])

This can be used later when creating a report.