Rik*_*Rik 12 vba function return-value
所有,
我想写一个函数来返回一个整数数组,所以我可以索引它们,但我不知道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)
Run Code Online (Sandbox Code Playgroud)
这些值都是整数,或者应该是,然后我可以索引我想要的stat的返回数组.谢谢.
-Rik
mof*_*tje 26
将函数作为数组赋予类型:
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
Run Code Online (Sandbox Code Playgroud)
我将在这里添加一个答案,因为我很高兴地说,经过几个小时的挫折和错误信息,我终于知道如何返回数组了!以下是从函数返回数组的方法:
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
Run Code Online (Sandbox Code Playgroud)
我在这里提出的评论非常重要。虽然 VBA 通常相当宽松,但这个特殊的东西却非常挑剔。这些是您的职能、任务和返回工作所必需的:
Function getStats() As Variant
Run Code Online (Sandbox Code Playgroud)
getStats现在是一个数组,而不是一个整数
| 归档时间: |
|
| 查看次数: |
55496 次 |
| 最近记录: |