Power Query code to change column types of variable # of columns

macfuller

Active Member
Joined
Apr 30, 2014
Messages
319
Office Version
  1. 365
Platform
  1. Windows
I would like the Power Query equivalent of a For...Next loop to change a variable number of column types.

I import a matrix of which the column names and column count after the 3rd column are variable. Columns 4 thru x come in as type Any and I'd like to convert them to Decimal. I believe I can refer to a column via Table.ColumnNames(tblName){x} but I'm not sure how I could loop through them to make sure all are converted.

The column headers of the matrix are equipment types which the users can adjust depending on which process they're modelling and thus which pieces of equipment are needed. Right now the query is hard-coded with the column names so each iteration requires the query to be changed to the new column names. I'm hoping this is something as simple as an .OtherColumns type of parameter.
 

Excel Facts

Show numbers in thousands?
Use a custom number format of #,##0,K. Each comma after the final 0 will divide the displayed number by another thousand
This should work:

Code:
let
    Source = Excel.CurrentWorkbook(){[Name="Table1"]}[Content],
    Schema = Table.Schema(Source),
    #"Filtered Rows" = Table.SelectRows(Schema, each [Position] >= 3),
    #"Removed Other Columns" = Table.SelectColumns(#"Filtered Rows",{List.First(Table.ColumnNames(#"Filtered Rows"))}),
    ListHeaders = Table.ToList(#"Removed Other Columns"),
    Count = List.Count(ListHeaders),
    Transform = Table.TransformColumnTypes(Source, Table.ToRows(Table.FromColumns({ListHeaders, List.Repeat({type number}, Count)})))
in
    Transform
 
Upvote 0

Forum statistics

Threads
1,223,903
Messages
6,175,286
Members
452,631
Latest member
a_potato

We've detected that you are using an adblocker.

We have a great community of people providing Excel help here, but the hosting costs are enormous. You can help keep this site running by allowing ads on MrExcel.com.
Allow Ads at MrExcel

Which adblocker are you using?

Disable AdBlock

Follow these easy steps to disable AdBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the icon in the browser’s toolbar.
2)Click on the "Pause on this site" option.
Go back

Disable AdBlock Plus

Follow these easy steps to disable AdBlock Plus

1)Click on the icon in the browser’s toolbar.
2)Click on the toggle to disable it for "mrexcel.com".
Go back

Disable uBlock Origin

Follow these easy steps to disable uBlock Origin

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back

Disable uBlock

Follow these easy steps to disable uBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back
Back
Top