I'm working on a Power Query M script to rename columns in a table based on certain conditions. However, I'm encountering a "Token Literal Expected" error when trying to use the try
expression within a List.MatchesAny
function. Here’s the relevant portion of my code:
RenameColumnsFunction = (table as table) as table =>
let ColumnNames = Table.ColumnNames(table),
//Apply transformation logic to each column name
RenamedColumns = List.Transform(ColumnNames, (colName) =>
// If any column values have a length of 4 and are numeric, rename the column to "Org level 2 Code"
if
List.MatchesAny(Table.Column(table, colName), each try
Text.Length(Text.From(_)) = 4 and **try **
Number.FromText(Text.From(_)) <> null otherwise false)
then
{colName, "Org Level 2 Code"}
// If the column name matches one of the predefined names, rename it to "Headcount Label"
else if
List.Contains({"ACCTG", "ADMIN", "ASM", "AWE", "CFO", "CROCOL", "CUSTSRV", "DEV", "ENGIN","FIN","FLDSP", "HOM", "HR","IT", "MERCH", "PROSVC"}, colName)
then
{colName, "Headcount Label"}
else {colName, colName} // Keep the original name if no match
),
RenamedTable = Table.RenameColumns(table, RenamedColumns, MissingField.Ignore)
in RenamedTable,
// Step 4: Apply the renaming function to each table query
ApplyRename = Table.AddColumn(FilteredQueries, "Transformed Data", each RenameColumnsFunction([Content])),
// Step 5: Expand the renamed tables (ensure there's data to extract)
RenamedTables = Table.ExpandTableColumn(ApplyRename, "Transformed Data", Table.ColumnNames(ApplyRename[Content]{0})),
// Step 6: Combine all queries into one table if needed
CombinedData = Table.Combine(RenamedTables[TransformedData])
in
CombinedData
Function to rename columns in a table
//function fRename
(xtable as table) as table =>
let names=Table.ColumnNames(xtable),
z = List.Transform(names, each
let a=_,
b= Value.Is(Value.FromText(a), type number) in
if Text.Length(a)=4 and b then "Org Level 2 Code" else
if List.Contains({"ACCTG", "ADMIN", "ASM", "AWE", "CFO", "CROCOL", "CUSTSRV", "DEV", "ENGIN","FIN","FLDSP", "HOM", "HR","IT", "MERCH", "PROSVC"}, a) then "Headcount Label"
else a
),
#"Rename"=Table.RenameColumns(xtable,List.Zip({names,z}))
in #"Rename"
And to use it
let Source = Excel.CurrentWorkbook(){[Name="Table1"]}[Content],
#"Process"=fRename(Source)
in #"Process"