作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我正在努力使现有的启用宏的电子表格能够在 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
但是,如果您在该过程中调用它两次,则会收到错误运行时错误'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
解决方案
重新创建数组。请参阅此示例。
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
关于arrays - Excel for Mac 2011 : UBound() Not Working,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16241554/
我是一名优秀的程序员,十分优秀!