I am getting the error "Length cannot be less than zero"

Hi Guys,

i am getting an error in my code (please see below)

I have used the code: Trim (Name.Substring(0, Name.IndexOf(“WR”))).Split(" "c).Last
In the assign activity.

can anybody help me here?

@nick.v I guess the Name variable doesn’t contain “WR” in it. Can you check the value of Name

1 Like

@supermanPunch your right it doesn’t have “WR” in it, how do i change the code to accommodate that?

@nick.v That depends on your requirement :sweat_smile: . What do you want to do when the WR is not present ?

@supermanPunch i looking for the bot to match the last name on the google sheet column the bot is extracting the data from to the webpage. If it matches then do this, else do this.

The WR number will not be present as theres code before it in the workflow that eliminate the WR

@nick.v Before Performing that Trim Operation you can use an If Activity to Check if the Name contains “WR” in this way :

and then you can use the Trim operation in the Then block and in else block do other operation what you have to do.

The Name variable doesn’t contain “WR” therefore i wouldn’t need to do an IF statement, would just need a code that takes the last name out of the variable. I just dont know how to change my code to achieve this outcome. @supermanPunch

@nick.v I need to Check the Values that you will have for the Name variable :sweat_smile:

its a string variable, it will have multiple words e.g. first name middle name last name etc there will not be any other characters in the variable.

@nick.v Is your Last Name Always a Single Word and is it separated by a Space. If so, then use this expression :


that code you have provided annoyingly isn’t providing the last name, it still has the full name @supermanPunch this is so frustrating

@nick.v Can you show the data in the Name variable Before using that Split and After using that Split method.

If your string variable contains the following example names:

“John Smith” or “John Doe Smith”

Then, this should work fine: Trim(Name.Split(" "c).Last)

So Name.IndexOf(“WR”) will return a -1 if WR is not the string contained in the variable name. and since you where using that to return the length of the new string to include in the old, if WR is not found then the substring part is told that it has to put in less then 0 characters from the other string. which is impossible. That’s why it crashes.

there’s a few ways it could be handled.

if( Name.IndexOf(“WR”) = -1 )
     Name.Split(" "c).Last.trim
    (Name.Substring(0, Name.IndexOf(“WR”))).Split(" "c).Last.trim

2 assuming WR is at the end of the string, since your code would cut off the WR and anything after it if it where there I’m assuming this is the case this will also work

System.Text.RegularExpressions.Regex.Replace(Name,"WR$","").Split(" "c).Last