【问题标题】:Passing array to function returns "Compile error: Type mismatch: array or user-defined type expected"将数组传递给函数返回“编译错误:类型不匹配:需要数组或用户定义类型”
【发布时间】: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

标签: vba excel


【解决方案1】:

变体(可能恰好包含一个数组)与变体数组不同。您需要更改此行:

Dim arr As Variant

到这里:

Dim arr() As Variant

【讨论】:

  • 谢谢,这成功了。那么Dim arr As Variant 是包含变体的数组,Dim arr() As Variant 是变体数组?我说的对吗?
  • 不完全是:Dim arr As Variant 是一个恰好包含一个数组的Variant
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2013-10-31
  • 2016-07-16
  • 1970-01-01
  • 1970-01-01
  • 2019-07-28
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多