Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Excel for Mac 2011: UBound() Not Working

I'm working on making an existing macro-enabled spreadsheet functional on Excel for Mac 2011.

I have a function (Source) that searches arrays for a specified value:

Function IsInArray(stringToBeFound As String, arr As Variant) As Boolean
  IsInArray = (UBound(Filter(arr, stringToBeFound)) > -1)
End Function

It works perfectly in Excel 2013, but on Excel for Mac 2011, I receive the error:

Runtime error '9': Subscript out of range

I broke it apart and found that the UBound call is what's causing the error.

I'd like to change as little as possible for maintainability. How can I fix this error for the Mac version?

Thanks in advance for any replies!

Edit: @Siddharth Rout's solution is spot on, but since I was searching arrays within a loop, I had to modify the loop to reset the array between each iteration as follows (in case anyone else runs into the same issue!):

' --- START Reset Array for OS X ---
Dim OS_X_Hack(99) As String

For intIndex = 0 To 99
    OS_X_Hack(intIndex) = Original(intIndex)
Next

Erase Original()
ReDim Original(0 To 99) As String

For intIndex = 0 To 99
    Original(intIndex) = OS_X_Hack(intIndex)
Next

Erase OS_X_Hack()
' --- END Reset Array for OS X ---
like image 263
Cameron Sumpter Avatar asked Oct 04 '22 07:10

Cameron Sumpter


1 Answers

Ok This is my observation. If you call the function once in a procedure then it will work fine. For Example

Sub Sample()
    Dim a As Variant
    Dim s As String
    Dim strTemp As String

    s = "CC"
    strTemp = "A,B,C,D"

    a = Split(strTemp, ",")

    Debug.Print IsInArray(s, a)
End Sub

Function IsInArray(stringToBeFound As String, arr As Variant) As Boolean
    IsInArray = (UBound(Filter(arr, stringToBeFound)) > -1)
End Function

enter image description here

However if you call it twice in the procedure then you will get an error Runtime error '9': Subscript out of range. Maybe it is an Excel 2011 Bug?

Sub Sample()
    Dim a As Variant
    Dim s As String
    Dim strTemp As String

    s = "CC"
    strTemp = "A,B,C,D"

    a = Split(strTemp, ",")

    Debug.Print IsInArray(s, a)

    s = "A"
    Debug.Print IsInArray(s, a)
End Sub

enter image description here

Solution

Recreate the array. See this example.

Sub Sample()
    Dim a As Variant
    Dim s As String
    Dim strTemp As String

    s = "CC"
    strTemp = "A,B,C,D"

    a = Split(strTemp, ",")
    Debug.Print IsInArray(s, a)

    s = "A"
    a = Split(strTemp, ",")
    Debug.Print IsInArray(s, a)
End Sub

Function IsInArray(stringToBeFound As String, arr As Variant) As Boolean
    IsInArray = (UBound(Filter(arr, stringToBeFound)) > -1)
End Function

enter image description here

like image 131
Siddharth Rout Avatar answered Oct 12 '22 23:10

Siddharth Rout