Search code examples
excelpowerquerym

Excel Power Query - Stop query if record field does not exist


I'm running a query which returns a record with a number of fields. If the record contains the field 'CashField', the query continues as normal. However, if the field does NOT exist, is there a way to terminate the query cleanly and exit the function i.e. not subsequent steps from running?


let
    Source = Excel.CurrentWorkbook(){[Name="CASH_FLOW_QUERY"]}[Content],
    ...
    res = Record.HasFields(Source, "CashField"),
in
    res

Attempted if statements and error handling but no success


Solution

  • Are you really returning a record or a table?

    Are there column headers? enter image description here

    Then it is a table and use

    let Source =  #table({"aaa", "bbb","Cash Field"},{{"111","bbb","ccc"}}),
    x =  if List.Contains(Table.ColumnNames(Source),"Cash Field") then PutNameOfAnotherQueryorFunctionHere else null
    in x
    

    Is it a record?

    enter image description here

    then

    let Source = Record.FromTable(Table.FromRecords({[Name = "aaa", Value = 11],[Name = "bbb", Value = "Bob"],[Name = "CashField", Value = "14567"]})),
    x = if Record.HasFields(Source, "CashField") then PutNameOfAnotherQueryorFunctionHere else null
    in x