powerquerypq

Refine Custom Function in Power Query (get Running Total with Custom Function)


I created a Custom Function to get running total with 3 variables as below.

(SourceTable as table, ColumnName, optional NewAddedColumnName as text) => 
    let
        Add_Index = Table.AddIndexColumn(SourceTable, "Index", 1),
        Get_RT = List.Accumulate(List.Transform(ColumnName, Number.From), {0}, (s, c) => s & {List.Last(s) + c}),
        Add_RTColumn = Table.AddColumn(Add_Index, NewAddedColumnName??"Running Total", each Get_RT{[Index]}, type number),
        Remove_Index = Table.RemoveColumns(Add_RTColumn,{"Index"})
    in
        Remove_Index

//name this AddColumn_RT

image_function

And this is an example with the function above.

let
    Source = Excel.CurrentWorkbook(){[Name="Table1"]}[Content],
    Change_ColumnTypes = Table.TransformColumnTypes(Source, {{"Month", type date}}),
    GetRT_Sales = AddColumn_RT(Change_ColumnTypes, Change_ColumnTypes[Sales])  //applying the custom function here 
in
    GetRT_Sales

image_example

You can see the code as

GetRT_Sales = AddColumn_RT(Change_ColumnTypes, Change_ColumnTypes[Sales])

But I want to use a code like

GetRT_Sales = AddColumn_RT(Change_ColumnTypes, "Sales")

I want you to retreat my function, in order to use "Sales" instead of Change_ColumnTypes[Sales] as 2nd parameter of it. Change_ColumnTypes written already as the 1st parameter, so don't wanna write this again.

I mean how to bring list of values in a column by text-format-variable when making custom function, or set a text-format-variable as a name of column to bring list of values in the column, whatever. very difficult with my poor English.

So, here is another question. pls advise a prefer title of this post. Thanks!


Solution

  • try Table.Column(SourceTable,ColumnName) in place of ColumnName

    (SourceTable as table, ColumnName as text, optional NewAddedColumnName as text) => 
    let
        Add_Index = Table.AddIndexColumn(SourceTable, "Index", 1),
        Get_RT = List.Accumulate(List.Transform(Table.Column(SourceTable,ColumnName), Number.From), {0}, (s, c) => s & {List.Last(s) + c}),
        Add_RTColumn = Table.AddColumn(Add_Index, NewAddedColumnName??"Running Total", each Get_RT{[Index]}, type number),
        Remove_Index = Table.RemoveColumns(Add_RTColumn,{"Index"})
    in
        Remove_Index
    

    called with

    GetRT_Sales = AddColumn_RT(Change_ColumnTypes, "Sales")