Forum Discussion

datasith's avatar
datasith
Copper Contributor
Jun 14, 2021
Solved

Counter variable in Power Query each loop

 

 

 

 

 

    /* [Index] and [Initial Stock] are columns in the Table that I can reference. */ 
    /* I'm curious how to have an "i" variable accessible in the M code */
    #"Added Index II" = Table.AddColumn(#"Added Index", "Index II",
        i = 0
        each if [Initial Stock] > 0 then 
            [Index]
            i = [Index]
        else 
            [i]
        ),

 

 

 

 

 

I'm new to power query. I understand having variables is *not* the way to do things. But. While I get a grasp on the language, can someone help me implement the pseudocode above? I want to have a running variable inside my "each" loop which gets updated depending on the condition. The hope is that the variable is created/modified from m-code, and not referenced from the data source. Again, sorry if this is not possible, I'm just getting started.

  • Hi datasith,

     

    This series article might put you back on track:

    https://www.data-insights.de/loops-in-m-recursion/

     

    https://www.data-insights.de/loops-in-m-language-list.generate/

     

    https://www.data-insights.de/part-3-for-next-loop-using-list-accumulate-in-m-for-power-query/

     

    Hope that helps you.

     

    cheers

     

2 Replies

  • Yea_So's avatar
    Yea_So
    Bronze Contributor

    Hi datasith,

     

    This series article might put you back on track:

    https://www.data-insights.de/loops-in-m-recursion/

     

    https://www.data-insights.de/loops-in-m-language-list.generate/

     

    https://www.data-insights.de/part-3-for-next-loop-using-list-accumulate-in-m-for-power-query/

     

    Hope that helps you.

     

    cheers

     

  • SergeiBaklan's avatar
    SergeiBaklan
    Diamond Contributor

    datasith 

    That will be easier if you explain what shall be in column Index II. If index in it for each zero Initial Stock shall be the same as for the previous non-zero, you may create column with

    ... each if [Initial Stock] > 0 then [Index] else null

    and fill down after that.

Resources