Adding or multiplying variants in VBA

后端 未结 2 1153
旧时难觅i
旧时难觅i 2020-12-11 12:15

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

相关标签:
2条回答
  • 2020-12-11 13:04

    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

    0 讨论(0)
  • 2020-12-11 13:14

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

    0 讨论(0)
提交回复
热议问题