有没有更好的方法来创建返回数组的函数:
function foo
Dim bar(1 to 2)as double
bar(1)=1
bar(2)=2
foo=bar
end function
并在代码中:
arrayx=foo
因为当我声明
Dim arrayx(1 to 2) as double
时它会抛出错误“无法分配数组”当我不声明变量 arrayx 时它似乎没有任何问题。
正如Matt建议,这个错误:
编译错误:无法分配给数组
源于您尝试将
Foo()
的返回值分配给 fixed 数组,而不是动态数组。您只需向编译器表明您声明的变量是一个数组,而不是数组的实际大小。它将根据返回的数组的大小计算出大小。
此外,您应该始终为函数指定返回值类型。在 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
此代码显示一个值为“1”的消息框,正如预期的那样。
您只能分配给动态数组。尝试:
Dim arrayx() as Double
如果您使用的小数组只有几个值,那么您也可以使用 byRef 而不是 byVal。
Private Function Foo(ByVal inputValue as Integer, Optional ByRef StrVal1 As String = "", Optional ByRef IntVal1 As Integer = 0) As String
If inputValue<123 Then
Foo = "Some string"
StrVal1 = "Str one"
IntVal1 = 27
Else
StrVal1 = "Str two"
IntVal1 = 321
End If
End Function
或
Private Sub Foo(ByVal inputValue as Integer, Optional ByRef StrVal1 As String = "", Optional ByRef IntVal12 As Integer = 0)
StrVal1 = "Str one"
IntVal1 = 27
End Function
Dim A$, B$, C$
A$ = Foo(1999, $B, $C)
Debug.Print A$
Debug.Print B$
Debug.Print C$