在OS X 10.7.5下的MacExcel2011中,我得到了一个我不理解的运行时错误。以下是代码的摘要:
Dim h, n, k as Integer
Dim report as Workbook
Dim r1 as Worksheet
Dim t, newline as String
Dim line() as String
newline = vbCr
'
' (code to get user input from a text box, to select a worksheet by number)
'
ReDim line(report.Sheets.Count + 10)
MsgBox "Array line has " & UBound(line) & " elements." '----> 21 elements
line = split(t, newline)
h = UBound(line)
MsgBox "Array line has " & h & " elements." '----> 16 elements
n = 0
MsgBox TypeName(n) '----> Integer
For k = h To 1 Step -1
If IsNumeric(line(k)) Then
n = line(k)
Exit For
End If
Next k
If n > 0 Then
MsgBox n '----> 7
MsgBox TypeName(n) '----> String
Set r1 = report.Sheets(n) '----> Runtime error "Subscript out of bounds"因此,n被声明为整数,但现在VBA认为它是一个字符串,并查找名为"7“的工作表。这是一个平台错误,或者是我还没有学到的东西?
同样让我惊讶的是,将数据放入动态数组会降低它的维数,但这可能是正常的,或者对于动态数组,Ubound返回最后使用的元素而不是维数,尽管我还没有看到文档说明这一点。
发布于 2016-04-12 08:35:11
您的问题的第一部分由@ScottCraner在注释中回答-在一行中声明多个强类型变量的正确语法是:
Dim h As Integer, n As Integer, k As Integer
'...
Dim t As String, newline As String所以,我将回答你的问题中与UBound相关的第二部分--除非你在模块的顶部声明了Option Base 1,否则你的数组默认从元素0开始,而不是从元素1开始。然而,Split函数总是返回一个基于0的数组(除非你拆分了一个vbNullString,在这种情况下你得到的LBound是-1):
Private Sub ArrayBounds()
Dim foo() As String
'Always returns 3, regardless of Option Base:
foo = Split("zero,one,two,three", ",")
MsgBox UBound(foo)
ReDim foo(4)
'Option Base 1 returns 1,4
'Option Base 0 (default) returns 0,3
MsgBox LBound(foo) & "," & UBound(foo)
End Sub这意味着这句话极具误导性。
h = UBound(line)
MsgBox "Array line has " & h & " elements."数组行实际上有h +1个元素,这意味着你的循环在这里...
For k = h To 1 Step -1
If IsNumeric(line(k)) Then
n = line(k)
Exit For
End If
Next k...is实际上正在跳过元素0。您甚至根本不需要h变量-您只需将循环参数设置为...
For k = UBound(line) To LBound(line) Step -1
If IsNumeric(line(k)) Then
n = line(k)
Exit For
End If
Next k...and不必担心数组的基是什么。
顺便说一句,没有问,但在这里将vbCr存储为变量...
newline = vbCr...是完全不必要的,如果你打算让“换行符”总是vbCr的话,它会为所有其他类型的问题打开大门。直接使用预定义的常量vbCr即可。
https://stackoverflow.com/questions/36560507
复制相似问题