Search code examples
arraysvbscripthp-uft

Subscript out of range when trying to get last item of an Array


For example, I have a string A-456-BC-123;DEF-456;GHI-789. And I need to search for second part:DEF-456 with keyword 456. The potential problem here is that the first part A-456-BC-123 also has the keyword 456. Currently my logic is that, split the string first using ;, split each of it again using -, get the last item of this Array, search keyword 456. Another thing is that I don't want to do a full keyword match like DEF-456, I only want to use 456 as keyword to locate DEF-456, in other words, 456 should be the last segment of the string I want.

Here are my codes:

FirstSplit= split("A-456-BC-123;DEF-456;GHI-789",";")

For each code in FirstSplit
    SecondSplit = split(FirstSplit,"-")
    'get Array Count
    Count = Ubound(SecondSplit)
    'get the last item in Array
    If SecondSplit(Count-1) = "456" Then
      'doing something
    End if
Next

Currently, an error will generate at SecondSplit(Count-1), saying that "Subscript out of range: '[number: -1]'"

Could someone tell me how to fix it?


Solution

  • The real problem is here:

    SecondSplit = Split(FirstSplit, "-")
    

    You should be splitting your element which you've stored in variable code from your For Each loop. By trying to split an array you should be getting a Type Mismatch error, but perhaps vbscript is forgiving enough to attempt and return a 0 element array back or something. Anyway:

    SecondSplit = Split(Code, "-")
    

    Also, to look at the last element just use:

    If secondSplit(Ubound(SecondSplit)) = "456" Then
    

    Subtracting 1 from the ubound would get you the second to last element.