Skip to main content
cancel
Showing results for 
Search instead for 
Did you mean: 

Enhance your career with this limited time 50% discount on Fabric and Power BI exams. Ends August 31st. Request your voucher.

Reply
AJose
Helper I
Helper I

Can i select the columns with Table.SelectColumns based on a condition - M Code?

I have a parameter which decides which column to select from a table. If the parametet value is "A", "Column1" should be selected and if the parametet value is "B", "Column2" should be selected . Can I do this with Table.SelectColumns in M code?

1 REPLY 1
edhans
Super User
Super User

Yes. You need to convert the A to 1, B to 2, etc. You can do that with the following assuming your letter is in the Code column:

=Character.ToNumber([Code])-64

The following M code imports a 9 column Excel table, adds the Char Code (above) then gives you the column name of the column referred to by the code.

 

let
    Source = Excel.CurrentWorkbook(){[Name="Table4"]}[Content],
    #"Changed Type" = Table.TransformColumnTypes(Source,{{"Code", type text}, {"Column A", type text}, {"Column A2", type text}, {"Column A3", type text}, {"Column A4", type text}, {"Column A5", type text}, {"Column A6", type text}, {"Column A7", type text}, {"Column A8", type text}}),
    #"Added Char Code" = Table.AddColumn(#"Changed Type", "Char Code", each Character.ToNumber([Code])-64, Int64.Type),
    #"Added Custom1" = Table.AddColumn(#"Added Char Code", "Relative Column Name", each Table.ColumnNames(#"Added Char Code"){[Char Code]})
in
    #"Added Custom1"


Did I answer your question? Mark my post as a solution!
Did my answers help arrive at a solution? Give it a kudos by clicking the Thumbs Up!

DAX is for Analysis. Power Query is for Data Modeling


Proud to be a Super User!

MCSA: BI Reporting

Helpful resources

Announcements
July 2025 community update carousel

Fabric Community Update - July 2025

Find out what's new and trending in the Fabric community.

July PBI25 Carousel

Power BI Monthly Update - July 2025

Check out the July 2025 Power BI update to learn about new features.