【发布时间】:2015-10-29 14:42:29
【问题描述】:
我有以下打印数组元素的子程序:
Sub printArray(arr() As Variant)
Dim i, lowerBound, upperBound As Integer
lowerBound = LBound(arr)
upperBound = UBound(arr)
MsgBox "lowerBound: " & lowerBound
MsgBox "upperBound: " & upperBound
For i = lowerBound To upperBound
MsgBox i & " : " & arr(i)
Next i
End Sub
这是按预期工作的,我按以下方式调用它:
Sub callPrintArray()
Dim arr(3) As Variant
arr(0) = "John"
arr(1) = "Star"
arr(2) = #6/30/2010# ' Hire Date
' PRINTS ONE EXTRA ELEMENT WITHOUT THIS LINE
' Dim arr(3) As Variant MEANS INDEXING FROM 0 TO 2
arr(3) = "LAST"
Call printArray(arr)
End Sub
然后我有将现有工作表作为数组返回的函数:
Function getListOfSheetsW() As Variant
Dim i As Integer
Dim sheetNames() As Variant
ReDim sheetNames(1 To Sheets.Count)
For i = 1 To Sheets.Count
sheetNames(i) = Sheets(i).Name
Next i
getListOfSheetsW = sheetNames
End Function
我想使用提到的子程序printArray 打印此函数返回的工作表。我试过了:
Sub callGetListOfSheetsW()
Dim arr As Variant
arr = getListOfSheetsW()
' Working
MsgBox arr(1)
MsgBox arr(2)
' Does not working
' Call printArray(arr)
End Sub
当我打印特定元素时它正在工作,但是当我想使用 printArray 打印整个数组时它不是,我得到:
编译错误:类型不匹配:需要数组或用户定义类型。
我做错了什么?
【问题讨论】:
-
@pnuts 你能解释一下你是如何让
Compile error: Type mismatch: array or user-defined type expected.消息出现在黄色框中的吗?谢谢。 -
注意,在写
Dim i, lowerBound, upperBound As Integer的时候,只有upperBound定义为Integer,i和lowerBound确实是Variant类型。您需要为每个变量使用As Interger。