VBA to change Data type of a Power Query loaded table

Bubna, Shreya 61 Reputation points
2021-03-05T11:32:24.863+00:00

I have tables loaded on my Excel from Power Query. Some columns do not retain the data type and format I have specified in power query. For Example: Percentage type changes to Decimal(87.82%>0.878236484) and date type changes to Number(1/1/2020>43831)

I hope to write VBA code to change the column data type by specifying the table field header.

Kindly help with this.

Thank you.

Not Monitored
Not Monitored
Tag not monitored by Microsoft.
36,152 questions
{count} votes

Accepted answer
  1. Lz._ 8,991 Reputation points
    2021-03-06T14:41:03.877+00:00

    @Bubna, Shreya

    If that's enough to run it from the sheet where table "ABC" exists, in a VBA module:

    Option Explicit  
      
    Sub FormatPercentColumn()  
        Dim TargetTable     As ListObject  
        Dim c               As ListColumn  
          
        Set TargetTable = ActiveSheet.ListObjects("ABC")  
        For Each c In TargetTable.ListColumns  
            If c.Name = "LR" Then  
                c.DataBodyRange.NumberFormat = "0.00%"  
                Exit For  
            End If  
        Next  
    End Sub  
    

2 additional answers

Sort by: Most helpful
  1. Lz._ 8,991 Reputation points
    2021-03-07T06:11:58.793+00:00

    @Bubna, Shreya

    Re. In my Excel Table called "ABC" I have a number of Percent Columns "GH%" , "AD%" etc. I want to write a code which would change the Data type of these Percent Columns which have "%" in their Column headers to type Percentage

    Sub FormatPercentColumns()  
        Dim TargetTable     As ListObject  
        Dim c               As ListColumn  
          
        Set TargetTable = ActiveSheet.ListObjects("ABC")  
        For Each c In TargetTable.ListColumns  
            If InStr(1, c.Name, "%") Then _  
                c.DataBodyRange.NumberFormat = "0.00%"  
        Next  
    End Sub  
    

    Just in case: Office VBA Reference is avail. here & if you have other VBA issues please open seperate threads as this one becomes confusing for those who search the site - Thanks

    1 person found this answer helpful.

  2. Bubna, Shreya 61 Reputation points
    2021-03-06T12:37:22.443+00:00

    Hello @Lz._ ,

    Thank you for your help. By a table field header i mean my power query loaded loaded excel table has a name "ABC" and the Percentage Coulumn also has a fixed name "LR". Using these can i write VBA to change data type to Percentage.

    Thank you.