vbscriptasp-classic

Type mismatch: 'UBound'


Why do I get this error;

Type mismatch: 'UBound'

Function JumbleArray(ByVal aArray)
    Dim iUpper, iLower, iLoop, iSwapPos, varTmp
    iUpper = UBound(aArray)
    iLower = LBound(aArray)

    Randomize Timer
    For iLoop = iLower To iUpper
        iSwapPos = Int(Rnd * (iUpper + 1))

        varTmp = aArray(iLoop)
        aArray(iLoop) = aArray(iSwapPos)
        aArray(iSwapPos) = varTmp
    Next

    JumbleArray = aArray
End Function

Dim strTestArray
strTestArray = "1,2,3,4,5,6,7,8"

Shuffle = JumbleArray(strTestArray)

This code was proposed elsewhere but without any reports of it not working. It looks like it should work, but it does not.

The code shown here is everything that you need. By simply running the code you will see the error.


Solution

  • From what I can see there are two main issues.

    1. The function UBound() expects a valid array to return the upper bound, anything else will cause a Type mismatch error to be raised.

      The problem here is the function expects an Array but it is being passed a String (as mentioned in the comments). If the string contains a valid string array (a string that can be interpreted via delimiters to be a single dimension array) you can use the Split() function to translate the string into a valid array and IsArray() to check a valid array is returned.

    2. The function JumbleArray() returns an Array which cannot just be output to the page using Response.Write(). To output it you first need to check its a valid array using IsArray() then either use Join() to output the values or iterate over each element in the array using a loop.

    When calling the function try this;

    strTestArray = "1,2,3,4,5,6,7,8"
    Dim TestArray: TestArray = Split(strTestArray, ",")
    If IsArray(TestArray) Then
      TestArray = JumbleArray(TestArray)
      If IsArray(TestArray) Then
        Call Response.Write(Join(TestArray, ","))
      End If
    Else
      Call Response.Write("Not a valid array")
    End If