Cro*_*ley 5 arrays vb6 function
是否有更好的方法来创建函数返回数组:
function foo
Dim bar(1 to 2)as double
bar(1)=1
bar(2)=2
foo=bar
end function
Run Code Online (Sandbox Code Playgroud)
并在代码中:
arrayx=foo
Run Code Online (Sandbox Code Playgroud)
因为当我声明Dim arrayx(1 to 2) as double它抛出一个错误"无法分配数组"当我没有声明变量arrayx它似乎没有任何问题.
Cod*_*ray 13
正如马特所说,这个错误:
编译错误:无法分配给数组
从这个事实,你已经尽力的返回值赋给茎Foo()的固定阵列,而不是一个动态数组.您只需要向编译器指出您声明的变量是一个数组,而不是数组的实际大小.它将根据返回的数组大小计算出大小.
此外,您应始终为函数指定返回值类型.你可以在VB中通过As Type在函数声明的末尾放置一个子句来实现.在这种情况下,您需要一个双精度数组,写为Double().
因此,重写您的代码看起来像这样,并结合这两个变化:
Function Foo() As Double() ' note the specification of a return value
Dim bar(1 To 2) As Double
bar(1) = 1
bar(2) = 2
Foo = bar
End Function
Private Sub Command1_Click()
Dim arrayx() As Double ' note the declaration of a DYNAMIC array
arrayx = Foo()
MsgBox arrayx(1)
End Sub
Run Code Online (Sandbox Code Playgroud)
此代码显示一个值为"1"的消息框,正如预期的那样.