VBA什么时候不被要求改变variablestypes?

我得到一个运行时错误,我不明白在Mac OS X 10.7.5的Excel 2011中的Mac。 这里是代码的总结:

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认为它是一个string,并寻找名为“7”的工作表。 这是一个平台的错误,还是有什么我还没有学到什么?

这也令我感到惊讶的是,将数据放入dynamic数组会降低其维度,但也许这是正常的,或者对于dynamic数组,Ubound将返回最后使用的元素而不是维度,尽pipe我没有看到logging。

您的问题的第一部分由@ScottCraner在注释中回答 – 在一行中声明多个强typesvariables的正确语法是:

 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 ,在这种情况下你得到一个-1的LBound ):

 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." 

…因为Array行实际上有h + 1个元素,这意味着你的循环在这里…

 For k = h To 1 Step -1 If IsNumeric(line(k)) Then n = line(k) Exit For End If Next k 

实际上是跳过元素0 。 你甚至根本不需要hvariables – 你可以让你的循环参数为…

 For k = UBound(line) To LBound(line) Step -1 If IsNumeric(line(k)) Then n = line(k) Exit For End If Next k 

…而不必担心arrays的基础是什么

顺便说一句,没有问,但存储vbCr作为一个variables在这里…

 newline = vbCr 

如果你打算一个“换行”总是vbCr ,那么……根本就没有必要,并且为其他各种问题打开了大门。 只需直接使用预定义的常量vbCr即可。