有一个function报告2个输出最简单的方法

关于VBA中的函数,我有一个非常基本的问题。 基本上,我想创build一个函数,返回2个输出,一个标量和一个matrix。 用户应该能够将这些结果存储到VBA中的单独variables中,并将其显示在Excel电子表格中。

我的方法:

  • 我显然可以使用2个不同的function,但这不是优雅的,涉及到冗余计算

  • 我创build了一个具有2个属性的类,然后将我的函数定义为该类的一个实例,将我的标量和matrix存储为这些属性。 问题是,在这种情况下,我不知道如何在Excel中轻松显示我的结果。

    • 然而,我可以创build2个额外的函数,只读取第一个函数的相应(标量或matrix)输出,但这又会导致冗余计算。

我害怕我失去了一些真正基本的东西,希望你能给我一些指导方针…非常感谢您的帮助:)

您可以使用这两个属性创build一个类,并返回该类的新实例作为返回值。 那么你的调用代码将不得不读取两个属性。

你可以使用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,那么您可以完全忽略我。

如果你从工作表中调用这个(不pipe你的解决scheme是什么),我想你总是会有多个(2)调用函数。 假设它不会经常更改,您可能会caching函数的结果。 它不会停止通话,但它会停止一些额外的计算。

 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 Function 

最简单的方法? 大概:

 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 

然后访问你想要的任何属性,你可以:

  • 在VBA中(0将返回标量,2将返回matrix):

     Sub tst() Dim FunctionResult() As Variant Dim i As Long Dim j As Long FunctionResult = TwoOutputs MsgBox "Scalar: " & FunctionResult(0) For i = LBound(FunctionResult(1), 1) To UBound(FunctionResult(1), 1) For j = LBound(FunctionResult(1), 2) To UBound(FunctionResult(1), 2) MsgBox "Matrix loc(" & i & ", " & j & "): " & FunctionResult(1)(i, j) Next j Next i End Sub