Excel for Mac 2011:UBound()不起作用

时间:2013-04-26 16:56:50

标签: arrays excel excel-vba excel-vba-mac vba

我正在努力在Excel for Mac 2011上创建一个支持宏的电子表格。

我有一个函数(Source),它在数组中搜索指定的值:

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

它在Excel 2013中运行良好,但在Excel for Mac 2011上,我收到错误:

Runtime error '9': Subscript out of range

我将它拆开,发现UBound调用是造成错误的原因。

我想尽可能少地改变可维护性。如何修复Mac版本的此错误?

提前感谢您的回复!

编辑: @Siddharth Rout的解决方案很有用,但由于我在循环中搜索数组,我不得不修改循环以在每次迭代之间重置数组,如下所示(以防其他人)遇到同样的问题!):

' --- 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 ---

2 个答案:

答案 0 :(得分:4)

好的这是我的观察。如果您在一个程序中调用该函数一次,那么它将正常工作。例如

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

但是,如果您在程序中调用它两次,那么您将收到错误Runtime error '9': Subscript out of range。也许它是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

<强>解决方案

重新创建数组。见这个例子。

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

答案 1 :(得分:0)

此解决方案的功劳归于this answer by Brian Hinchey。使用下面的代码,我可以在Excel for Mac 2011的循环中调用IsInArray。

Function IsInArray(stringToBeFound As String, arr As Variant) As Boolean
  IsInArray = Not IsError(Application.Match(stringToBeFound, arr, 0))
End Function