Reputation: 454
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 ---
Upvotes: 5
Views: 1766
Reputation: 123
Credit for this solution goes to this answer by Brian Hinchey. Using the code below, I'm able to call IsInArray within a loop in Excel for Mac 2011.
Function IsInArray(stringToBeFound As String, arr As Variant) As Boolean
IsInArray = Not IsError(Application.Match(stringToBeFound, arr, 0))
End Function
Upvotes: 0
Reputation: 149305
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
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
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
Upvotes: 4