Adding or multiplying variants in VBA

流过昼夜 提交于 2019-11-28 13:02:20

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.)

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

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