gpt4 book ai didi

arrays - Excel for Mac 2011 : UBound() Not Working

转载 作者:行者123 更新时间:2023-12-02 08:05:46 26 4
gpt4 key购买 nike

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

最佳答案

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

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

但是,如果您在该过程中调用它两次,则会收到错误运行时错误'9':下标超出范围。也许这是 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

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

关于arrays - Excel for Mac 2011 : UBound() Not Working,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16241554/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com