1

I am using Power Query in Excel for Microsoft 365.

Please consider the following M Language code:

let
    Source = Excel.CurrentWorkbook(){[Name="Table1"]}[Content],
    #"Changed Type of all to Text" = Table.TransformColumnTypes(Source,{{"A", type text}, {"B", type text}, {"C", type text}}),
    #"Removed Unneeded Columns" = Table.RemoveColumns(#"Changed Type of all to Text",{"A"}),
    ...
in
    #"Removed Duplicate Rows"

The problem I'm running into is that column A is not always present in the source table. If it is present, it must be removed. However, including it in the M Language code induces an error in instances when it is not present.

How may I change my M Language code to effectively handle both the case of column A being present and the case of column A not being present?

2
  • Try selecting the columns you do want and then apply Remove Other Columns.
    – bugdrown
    Commented Aug 16, 2023 at 2:22
  • You could use try...otherwise; you could use Table.ColumnNames(#"Previous Step"); remove Column A from the list if it exists; then use Table.SelectColumns referencing that list. And I'm sure there are other methods also. Commented Aug 16, 2023 at 12:16

1 Answer 1

0

Restatement of the Original Problem

The problem I'm running into is that column A is not always present in the source table. If it is present, it must be removed. However, including it in the M Language code induces an error in instances when it is not present.

The Solution

As a preliminary, I'll note that when I first create the query by right-clicking on a cell in my source table and by then selecting Get Data from Table/Range..., two applied steps are automatically created:

  1. Source
  2. Changed Type

The solution to my problem is as follows:

  1. Insert a Choose Columns applied step between the Source and Changed Type applied steps and de-select column A if it is present (I may or may not be working with an instance of the source table that has column A in it)
  2. Edit the M Language code of the Changed Type applied step to remove the parameter corresponding to column A if it is present (I may or may not be working with an instance of the source table that has column A in it)

The key is to not reference column A in the M Language code (because an error will be thrown if it is referenced but is not present). So, rather than explicitly select column A for removal, just don't select it for inclusion.

Structuring the query this way allows it to be applied to source tables that either do or do not contain column A. It will work in both cases.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .