关于VBA中的函数,我有一个非常基本的问题。基本上,我想要创建一个函数,返回两个输出,一个标量和一个矩阵。用户应该能够将这些结果存储在VBA中的单独变量中,并在Excel电子表格中显示它们。
我的方法:
- I could however create 2 additional functions that would just read the respective (scalar or a matrix) output of the first function but this would again result in redundant computations.
恐怕我错过了一些最基本的东西,希望你能给我一些指导.非常感谢你的帮助:)
发布于 2013-08-16 20:26:02
您可以使用这两个属性创建一个类,并将该类的一个新实例作为返回值返回。那么您的调用代码必须同时读取这两个属性。
发布于 2013-08-16 20:34:34
最简单的方法?可能:
Function TwoOutputs() As Variant()
Dim matrix(1 To 2, 1 To 3) As Variant
matrix(1, 1) = "Did"
matrix(1, 2) = "it"
matrix(1, 3) = "work?"
matrix(2, 1) = "Yes"
matrix(2, 2) = "it"
matrix(2, 3) = "did!"
TwoOutputs = Array("scalar", matrix)
End Function然后,要访问您想要的任何属性,可以:
发布于 2013-08-16 20:56:46
你可以用ByRef。不过,可能不是最好的计划。
Sub Example(ByRef A As String, ByRef B As String)
A = A & "Hello"
B = B & "World!"
End Sub
Sub test()
Dim A As String
Dim B As String
A = "Test"
B = "Test"
Example A, B
Debug.Print A & " " & B
End Sub编辑
如果您试图在工作表上提供一个UDF,那么您可以完全无视我。
如果您从工作表中调用此函数(无论您的解决方案是什么),我认为您将始终有多个(2)调用函数。假设函数不会频繁更改,您可能能够缓存函数的结果。它不会停止呼叫,但它会停止一些多余的计算。
Private Cache As Object
Public Function MonsterFunction(ByVal A As Integer, ByVal B As Integer, Optional ByVal Add As Boolean = False) As Variant
Dim Key As String
Dim Result As Integer
Key = CStr(A) & IIf(Add, "+", "-") & CStr(B)
If Cache Is Nothing Then
Set Cache = CreateObject("Scripting.Dictionary")
End If
If Cache.Exists(Key) Then
MonsterFunction = Cache(Key)
Else
If Add Then
Result = A + B
Else
Result = A - B
End If
Cache.Add Key, Result
MonsterFunction = Result
End If
End Functionhttps://stackoverflow.com/questions/18281507
复制相似问题