Understand Variables in Microsoft Power FX - Power Platform - Microsoft Docs
Understand Variables in Microsoft Power FX - Power Platform - Microsoft Docs
In this article
Translate Excel into Power Fx
Know when to use variables
Use a global variable
Types of variables
Create and remove variables
Variable lifetime and initial value
Reading variables
Use a context variable (Power Apps only)
Use a collection
7 Note
Microsoft Power Fx is the new name for the canvas apps formula language. These
articles are work in progress as we extract the language from canvas apps, integrate it
with other Microsoft Power Platform products, and make it available as open source.
Start with the Microsoft Power Fx Overview for an introduction to the language.
If you've used another programming tool, such as Visual Basic or JavaScript, you may be
asking: Where are the variables? Microsoft Power Fx is a little different and requires a
different approach. Instead of reaching for a variable when you write a formula, ask
yourself: What would I do in a spreadsheet?
In other tools, you may have explicitly performed a calculation and stored the result in a
variable. However, Power Fx and Excel both automatically recalculate formulas as the input
data changes, so you usually don't need to create and update variables. By taking this
approach whenever possible, you can more easily create, understand, and maintain your
app.
In some cases, you'll need to use variables in Power Fx, which extends Excel's model by
adding behavior formulas. These formulas run when, for example, a user selects a button.
Within a behavior formula, it's often helpful to set a variable to be used in other formulas.
In general, avoid using variables. But sometimes only a variable can enable the experience
you want. Variables are implicitly created and typed when they appear in functions that set
their values.
Excel doesn't have variables. The value of a cell that contains a formula changes based on
its input, but there's no way to remember the result of a formula and store it in a cell or
anywhere else. If you change a cell's value, the entire spreadsheet may change, and any
previously calculated values are lost. An Excel user can copy and paste cells, but that's
under the user's manual control and isn't possible with formulas.
Power Fx
Logic that you create in Power Fx behaves very much like Excel. Instead of updating cells,
you can add controls wherever you want on a screen and name them for use in formulas.
For example in Power Apps, you can replicate the Excel behavior in an app by adding a
Label control, named Label1, and two Text input controls, named TextInput1 and
TextInput2. If you then set the Text property of Label1 to TextInput1 + TextInput2, it will
always show the sum of whatever numbers are in TextInput1 and TextInput2 automatically.
Notice that the Label1 control is selected, showing its Text formula in the formula bar at
the top of the screen. Here we find the formula TextInput1 + TextInput2. This formula
creates a dependency between these controls, just as dependencies are created between
cells in an Excel workbook. Let's change the value of TextInput1:
The formula for Label1 has been automatically recalculated, showing the new value.
In Power Fx, you can use formulas to determine not only the primary value of a control but
also properties such as formatting. In the next example, a formula for the Color property of
the label will automatically show negative values in red. The If function should look familiar
from Excel:
If( Value(Label1.Text) < 0, Red, Black )
Benefits
Using formulas to build apps has many advantages:
If you know Excel, you know Power Fx. The model and formula language are the
same.
If you've used other programming tools, think about how much code would be
required to accomplish these examples. In Visual Basic, you'd need to write an event
handler for the change event on each text-input control. The code to perform the
calculation in each of these is redundant and could get out of sync, or you'd need to
write a common subroutine. In Power Fx, you accomplished all of that with a single,
one-line formula.
To understand where Label1's text is coming from, you know exactly where to look:
the formula in the Text property. There's no other way to affect the text of this
control. In a traditional programming tool, any event handler or subroutine could
change the value of the label, from anywhere in the program. This can make it hard to
track down when and where a variable was changed.
If the user changes a slider control and then changes their mind, they can change the
slider back to its original value. And it's as if nothing had ever changed: the app
shows the same control values as it did before. There are no ramifications for
experimenting and asking "what if," just as there are none in Excel.
In general, if you can achieve an effect by using a formula, you'll be better off. Let the
formula engine in Power Fx do the work for you.
77 is added to the
running total.
Our adding machine uses something that doesn't exist in Excel: a button. In this app, you
can't use only formulas to calculate the running total because its value depends on a series
of actions that the user takes. Instead, our running total must be recorded and updated
manually. Most programming tools store this information in a variable.
You'll sometimes need a variable for your app to behave the way you want. But the
approach comes with caveats:
You must manually update the running total. Automatic recalculation won't do it for
you.
The running total can no longer be calculated based on the values of other controls. It
depends on how many times the user selected the Add button and what value was in
the text-input control each time. Did the user enter 77 and select Add twice, or did
they specify 24 and 130 for each of the additions? You can't tell the difference after
the total has reached 154.
Changes to the total can come from different paths. In this example, both the Add
and Clear buttons can update the total. If the app doesn't behave the way you expect,
which button is causing the problem?
The first time that a user selects the Add button and Set runs, RunningTotal is set to
the value RunningTotal + TextInput1.
4. To set the running total to 0 whenever the user selects the Clear button, set its
OnSelect property to this formula:
Set( RunningTotal, 0 )
7. To show the global variable's value, select the File menu, and select Variables in the
left-hand pane.
8. To show all the places where the variable is defined and used, select it.
Types of variables
Power Fx has two types of variables:
Variables Scope Description Functions
type that
establish
Variables Scope Description Functions
type that
establish
Collections App Holds a table that can be referenced from anywhere Collect
in the app. Allows the contents of the table to be ClearCollect
modified rather than being set as a whole. Can be
saved to the local device for later use.
Context Screen Great for passing values to a screen, much like UpdateContext
variables parameters to a procedure in other languages. Navigate
Can be referenced from only one screen.
Reading variables
You use the variable's name to read its value. For example, you can define a variable with
this formula:
Set( Radius, 12 )
Then you can simply use Radius anywhere that you can use a number, and it will be
replaced with 12:
Pi() * Power( Radius, 2 )
If you give a context variable the same name as a global variable or a collection, the
context variable takes precedence. However, you can still reference the global variable or
collection if you use the disambiguation operator [@Radius].
The first time that the user selects the Add button and UpdateContext runs,
RunningTotal is set to the value RunningTotal + TextInput1.
4. To set the running total to 0 whenever the user selects the Clear button, set its
OnSelect property to this formula:
UpdateContext( { RunningTotal: 0 } )
Again, UpdateContext is used with the formula UpdateContext( { RunningTotal: 0 } ).
7. You can set the value of a context variable while navigating to a screen. This is useful
for passing "context" or "parameters" from one screen to another. To demonstrate
this technique, insert a screen, insert a button, and set its OnSelect property to this
formula:
Navigate( Screen1, None, { RunningTotal: -1000 } )
Hold down the Alt key while you select this button to both show Screen1 and set the
context variable RunningTotal to -1000.
8. To show the value of the context variable, select the File menu, and then select
Variables in the left-hand pane.
9. To show where the context variable is defined and used, select it.
Use a collection
Finally, let's look at creating our adding machine with a collection. Since a collection holds
a table that is easy to modify, we will make this adding machine keep a "paper tape" of
each value as they are entered.
How collections work:
Create and set collections by using the ClearCollect function. You can use the Collect
function instead, but it will effectively require another variable instead of replacing
the old one.
A collection is a kind of data source and, therefore, a table. To access a single value in
a collection, use the First function, and extract one field from the resulting record. If
you used a single value with ClearCollect, this will be the Value field, as in this
example:
First( VariableName ).Value
Let's recreate our adding machine by using a collection:
1. Add a Text input control, named TextInput1, and two buttons, named Button1 and
Button2.
2. Set the Text property of Button1 to "Add", and set the Text property of Button2 to
"Clear".
3. To update the running total whenever a user selects the Add button, set its OnSelect
property to this formula:
Collect( PaperTape, TextInput1.Text )
The mere existence of this formula establishes PaperTape as a collection that holds a
single-column table of text strings. You can reference PaperTape anywhere in this
app. Whenever a user opens this app, PaperTape is an empty table.
When this formula runs, it adds the new value to the end of the collection. Because
we're adding a single value, Collect automatically places it in a single-column table,
and the column's name is Value, which you'll use later.
4. To clear the paper tape when the user selects the Clear button, set its OnSelect
property to this formula:
Clear( PaperTape )
5. To display the running total, add a label, and set its Text property to this formula:
Sum( PaperTape, Value )
6. To run the adding machine, press F5 to open Preview, enter numbers in the text-input
control, and select buttons.
7. To return to the default workspace, press the Esc key.
8. To display the paper tape, insert a Data table control, and set its Items property to
this formula:
PaperTape
In the right-hand pane, select Edit fields and then select Add field, select Value
column and then select Add to show it.
9. To see the values in your collection, select Collections on the File menu.
10. To store and retrieve your collection, add two additional button controls, and set their
Text properties to Load and Save. Set the OnSelect property of the Load button to
this formula:
Clear( PaperTape ); LoadData( PaperTape, "StoredPaperTape", true )
You need to clear the collection first because LoadData will append the stored values
to the end of the collection.
11. Set the OnSelect property of the Save button to this formula:
SaveData( PaperTape, "StoredPaperTape" )
12. Preview again by pressing the F5 key, enter numbers in the text-input control, and
select buttons. Select the Save button. Close and reload the app, and select the Load
button to reload your collection.
Is this page helpful?
Yes No
Recommended content
Operators and Identifiers in Microsoft Power Fx - Power Platform
Reference information, including syntax and examples, for the operators and identifiers in
Microsoft Power Fx
Show more S