Search code examples
powerquerym

Where did I go wrong in this M-Code function for power-query?


I'm trying to write an M-Code function that I can use to filter out text values that aren't of the format "A0000" or "B0000" or "C0000" etc.

I tried my hand at writing a custom function in Power-Query, but the nuances of this language seem to escape me and the documentation and the syntax error warnings are pretty much useless in troubleshooting.

Here's what I have so far. I'm getting an error "Token Identifier Expected" which highlights the very first if line when I click the show error button.

Does anyone know where I've gone wrong here, and what I might try to fix it?

let IsNewPN= (Argument) =>
    let
        /*M code to evaluate in the function goes here*/
        a= Text.Start(Argument,1),
        b= Text.End(Argument, Text.Length(Argument) - 1),

        if     a="A" or a="B" or a="C" or a="D" or a="E" or a="F" or a="H" or a="M" or a="Q" or a="W"
        then    x=1
        else    x=0

        if x=0 
        then Result = "FALSE"
        else    Result=try a & Text.InferNumberType(b) otherwise "FALSE"
    in
        Result
in
    IsNewPN

Solution

  • Each line needs to be of the form value = expression.

    Try changing your code to this:

    let IsNewPN= (Argument) =>
        let
            /*M code to evaluate in the function goes here*/
            a= Text.Start(Argument,1),
            b= Text.End(Argument, Text.Length(Argument) - 1),
    
            x = 
            if     a="A" or a="B" or a="C" or a="D" or a="E" or a="F" or a="H" or a="M" or a="Q" or a="W"
            then    1
            else    0,
    
            Return = 
            if x=0 
            then "FALSE"
            else  try a & Text.InferNumberType(b) otherwise "FALSE"
        in
            Result
    in
        IsNewPN
    

    In this code, x and Return are the 'token identifiers` for their respective lines.


    Side note: You can simplify your big or expression using this instead:

    Text.Contains("ABCDEFHMQW",a)