所有
我想编写一个函数来返回一个整数数组,这样我就可以为它们编制索引,但我不知道VBA的语法。这是伪代码:
function getStats() as integer
dim returnVal(4) as integer
returnVal(0)=c2percent14
returnVal(1)=c3percent14
returnVal(2)=c4percent14
returnVal(3)=c5percent14
getStats=returnVal
end function
msgbox getStats(3)
这些值都是整数,或者应该是,然后我可以索引我想要的stat的返回数组。感谢。
-Rik
答案 0 :(得分:24)
将函数类型化为数组:
function getStats() as integer()
dim returnVal(4) as integer
returnVal(0) = c2percent14
returnVal(1) = c3percent14
returnVal(2) = c4percent14
returnVal(3) = c5percent14
getStats = returnVal
end function
Sub mysub()
Dim myArray(4) As String
myArray = getStats()
msgbox myArray(3)
end sub
答案 1 :(得分:6)
Function getStats() As Variant
getStats现在是一个数组,而不是一个整数
答案 2 :(得分:2)
我将在这里添加一个答案,因为我很高兴地说,经过数小时的沮丧和糟糕的信息,我终于知道如何返回数组!这是从函数返回数组的方法:
Sub mysub()
Dim i As Integer, s As String
Dim myArray() As Integer 'if you declare a size here you will get "Compile error, can't assign to array"
myArray = getStats()
s = "Array values returned:" & vbCrLf
For i = 0 To UBound(myArray)
s = (s & myArray(i) & " ")
Next
MsgBox s
End Sub
Function getStats() As Integer() 'The return type must be EXACTLY the same as the type declared in the calling sub.
Dim returnVal(2) As Integer 'if you DON'T declare a size here you will get "Run-time error '9': Subscript out of range"
returnVal(0) = 0
returnVal(1) = 1
returnVal(2) = 2
'returnVal(3) = 3 This will throw an error. Remember that an array declared (2) will hold 3 values, 0-2.
getStats = returnVal
End Function
我在此处包含的评论非常重要。尽管VBA通常很松懈,但是这一点非常挑剔。这些对于您的功能,分配和恢复工作是必需的: