5

我正在努力使现有的启用宏的电子表格在 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 ---
4

2 回答 2

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

在此处输入图像描述

但是,如果您在该过程中调用它两次,则会收到错误消息Runtime error '9': Subscript out of range。也许这是一个 Excel 2011 错误?

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

在此处输入图像描述

解决方案

重新创建数组。请参阅此示例。

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

在此处输入图像描述

于 2013-04-26T17:23:09.657 回答
0

这个解决方案的功劳归功于 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
于 2016-02-06T13:19:18.010 回答