Adding or multiplying variants in VBA

我们两清 提交于 2019-12-29 01:30:08

问题


Suppose we are given two variants, X and Y, that may be numbers, ranges or arrays. Is there a simple way to add or multiply them like in worksheet formulas =X+Y and =X*Y?

One possibility i thought of would be to use the Evaluate operation, something like this:

Dim X, Y

Sub AddMult()
    Dim Add, Mult
    X = Array(Array(1, 3), Array(2, 4))
    Y = Array(1, 2)
    Add = [GetX()+GetY()]
    Mult = [GetX()*GetY()]
End Sub
Function GetX()
    GetX = X
End Function
Function GetY()
    GetY = Y
End Function

It seems a little awkward though. Any other ideas?

(Here is a related question: Multiplying arrays with scalars and adding in VBA.)


回答1:


After looking at various options, i've settled on a Worksheetfunction method. The most viable candidates for arithmetic calculations appear to be in the financial category. From Excel help on the PV function when rate = 0, the following relation exists among the arguments: pmt * nper + pv + fv = 0. This relation also applies to each of the other corresponding functions. Therefore one option would be:

Sub AddMult()
    Dim X, Y, Add, Mult
    X = Array(Array(1, 3), Array(2, 4))
    Y = Array(1, 2)
    With Application
        Add = .Pmt(, -1, X, Y)
        Mult = .PV(, 1, .PV(, X, Y))
    End With
End Sub

For other operations on variants, further WorksheetFunction methods are available:

.SLN(x,y,1)     'x-y
.SLN(x,,y)      'x/y
.Power(x,y)     'x^y 
.Quotient(x,y)  'x\y 
.Delta(x,y)     'x=y
.GeStep(x,y)    'x>=y

Note: Prefix by Application (not Worksheetfunction which doesn't allow for other data types.)




回答2:


The provided code works in a Module. There the Functions GetX() and GetY() are UDFs and so [GetX()] and [GetY()] can evaluate them. But then your code possible is the best solution? Of course there are two UDFs and two variables in global scope. But another solution, which try to avoid this, would result in endless checking for possibilities what the Variants really contain.

Further tests have shown, that the functions in the Module can even be evaluated if they are declared private. Also the global variables must not to be public. So your solution is the best solution in my opinion.

Private X, Y

Sub AddMult()
    Dim Add, Mult
    X = [{4,5,6}]
    Set Y = Range("A1:C200")
    Add = [GetX() + GetY()]
    Mult = [GetX() * GetY()]
End Sub

Private Function GetX()
    GetX = X
End Function

Private Function GetY()
    GetY = Y
End Function

Greetings

Axel



来源:https://stackoverflow.com/questions/25575363/adding-or-multiplying-variants-in-vba

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!