We have 'chunks' of identical formulas in different parts of our app. In light of PA lacking actual named functions, are there any workarounds that would allow us to reuse a function/formula to prevent duplication of 'code' (i.e. formula)?
2 Answers
One option would be to create a hidden button or other selectable item and then assign the formula to this button. Whenever you need to rerun the formula, instead of recreating the formula, use Select(Button1).
For instance, if you need to have a formula that adds to a collection:
- Add a button called Button1.
- Set the Visible property to False
- Set the OnSelect property to something like
Collect(YourCollection,"A Value")
- Anywhere that needs to call this function set the OnSelect property to
Select(Button1)
If you need to set a dynamic value to this collection, you can set a context variable first
- Change the OnSelect property for Button1 to
Collect(YourCollection,yourVariable) - Set the OnSelect property of you control to
UpdateContext({yourVariable,"A Value"});Select(Button1)
Of course this is a very simple example and can be expanded upon.
Of course you can also go the Power Automate route, calling a Flow from within your PowerApp control to do your work, but that may require additional licensing if you do complex work within the Flow and return values then have to be parsed.
Here's hoping Microsoft eventually allows us to create custom functions that can be called within PowerApps.
This has just been announced, which allows makers to create user-defined formulas using components: https://powerapps.microsoft.com/en-us/blog/enhanced-component-properties/.
Here's an example from the blog post:
We can use property parameters in input and output properties too. A good example of this would would be a math utilities library. We don’t currently offer Excel’s RandBetween function in Power Apps. But, we can recreate it using the Rand function that we do support.
Let’s start by creating a new MathUtils component with a RandBetween custom property of property type Output and Data type Number:
We’ll add two parameters to this property for the range. Excel names these parameters Bottom and Top, of type Number. These are both required parameters in Excel.
And with the same thing done for Top:
Within the component, we’ll define the formula for calculating RandBetween based on these parameters:
If( Top >= Bottom, Round( Rand() * (Top - Bottom) + Bottom, 0 ), Blank() )Now we can call it like a function from within our app. We will need to create an instance of this component in our app, with the default name MathUtils_1. Here two slider controls are used as input and the result is shown in a label control:




