从子例程返回数组给出:编译错误:无法分配给数组

时间:2015-10-15 14:35:07

标签: arrays vba excel-vba excel

我的目标是从子程序返回数组。我一直在关注this教程。这是我的代码:

Function FuncReturnArray() As String
  Dim Films(1 To 5) As String
  Films(1) = "Lord of the Rings"
  Films(2) = "Speed"
  Films(3) = "Star Wars"
  Films(4) = "The Godfather"
  Films(5) = "Pulp Fiction"
  FuncReturnArray = Films
End Function

Sub SubReturnArray()
  Dim Films() As String
  Films = FuncReturnArray()
  MsgBox Films(4)
End Sub

Compile error: Can't assign to array并且编辑指向以下行:Films = FuncReturnArray()我做错了什么?

2 个答案:

答案 0 :(得分:3)

如此接近 - 你真的会为这一个踢自己:

Function FuncReturnArray() As String()
  Dim Films(1 To 5) As String
  Films(1) = "Lord of the Rings"
  Films(2) = "Speed"
  Films(3) = "Star Wars"
  Films(4) = "The Godfather"
  Films(5) = "Pulp Fiction"
  FuncReturnArray = Films
End Function

Sub SubReturnArray()
  Dim Films() As String
  Films = FuncReturnArray()
  MsgBox Films(4)
End Sub

注意上面代码中的第一行 - " String"需要遵循"()"表示FuncReturnArray是一个数组。您可能已经认为" FuncReturnArray"之后的括号这样做了,但实际上在那个上下文中它们是指那个没有参数传递给函数的事实。

答案 1 :(得分:1)

使您的函数成为变体类型。

co2overco()