Forum Discussion

Syndicate_Admin's avatar
Syndicate_Admin
Administrator
3 years ago
Solved

How To Dynamic Rename Column Headers: [Month] & [Current Year] in P. Query

I am new beginner of Power Query. My current raw data (1st screenshot below) consists of column headers (Column B - M) without [Year Name].    Column A Column B Column C Column D Column E C...
  • v-yanjiang-msft's avatar
    3 years ago

    Hi Syndicate_Admin ,

    According to your description, here's my solution. Add the step in Advanced Editor:

    #"Rename"=let 
    _Year=Text.From(Date.Year(Date.From(DateTime.LocalNow()))) 
    in 
    Table.RenameColumns(#"Removed Columns2",{{"Jan", "Jan "&_Year}, {"Feb", "Feb "&_Year}, {"Mar", "Mar "&_Year}, {"Apr", "Apr "&_Year}, {"May", "May "&_Year}, {"Jun", "Jun "&_Year}, {"Jul", "Jul "&_Year}, {"Aug", "Aug "&_Year}, {"Sep", "Sep "&_Year}, {"Oct", "Oct "&_Year}, {"Nov", "Nov "&_Year}, {"Dec", "Dec "&_Year}})

    I define a variable _Year in the code, which will automatically get the current year. When year 2023 comes, it will automatically changes to 2023 without enter in the Excel.

    Here's the whole M syntax, you can copy-paste in a blank query.

    let
        Source = Table.FromRows(Json.Document(Binary.Decompress(Binary.FromText("i45WMlTSUTICYmMgNgFiUyA2A2JzILYAYksgNjQAESCVhkZKsbEA", BinaryEncoding.Base64), Compression.Deflate)), let _t = ((type nullable text) meta [Serialized.Text = true]) in type table [Jan = _t, Feb = _t, Mar = _t, Apr = _t, May = _t, Jun = _t, Jul = _t, Aug = _t, Sep = _t, Oct = _t, Nov = _t, Dec = _t]),
        #"Removed Columns2" = Table.TransformColumnTypes(Source,{{"Jan", Int64.Type}, {"Feb", Int64.Type}, {"Mar", Int64.Type}, {"Apr", Int64.Type}, {"May", Int64.Type}, {"Jun", Int64.Type}, {"Jul", Int64.Type}, {"Aug", Int64.Type}, {"Sep", Int64.Type}, {"Oct", Int64.Type}, {"Nov", Int64.Type}, {"Dec", Int64.Type}}),
        #"Rename"=let _Year=Text.From(Date.Year(Date.From(DateTime.LocalNow()))) in Table.RenameColumns(#"Removed Columns2",{{"Jan", "Jan "&_Year}, {"Feb", "Feb "&_Year}, {"Mar", "Mar "&_Year}, {"Apr", "Apr "&_Year}, {"May", "May "&_Year}, {"Jun", "Jun "&_Year}, {"Jul", "Jul "&_Year}, {"Aug", "Aug "&_Year}, {"Sep", "Sep "&_Year}, {"Oct", "Oct "&_Year}, {"Nov", "Nov "&_Year}, {"Dec", "Dec "&_Year}})
    in
        #"Rename"

    Result:

    I attach my sample below for your reference.

     

    Best Regards,
    Community Support Team _ kalyj

    If this post helps, then please consider Accept it as the solution to help the other members find it more quickly.