0

I am totally new to VBA and was asked to create a function that adds the numerical values of two cells.

I came up with the following, but I am given the message

Compile Error: Cannot assign to array, with Additionex

at the bottom marked as the problem…

Could anybody help out?

Function Additionex(num1 As Double, num2 As Double) As Double()
    Dim num3 As Double

    num3 = num1 + num2

    Additionex = num3
End Function
0

3 Answers 3

1

Double() is an array of Double-type variables. You want as Double.

Function Additionex(num1 As Double, num2 As Double) As Double

    Dim num3 As Double

    num3 = num1 + num2

    Additionex = num3

End Function
Sign up to request clarification or add additional context in comments.

Comments

1

You can also use Evaluate

Public Function Additionex(ByVal num1 As Double, ByVal num2 As Double) As Double
    Additionex = Evaluate(num1 + num2)
End Function

If you want something more generic that takes ranges (your two cells as arguments) and can handle errors consider something like:

Public Function Additionex(ByVal cell1 As Range, ByVal cell2 As Range) As Variant
    If IsNumeric(cell1.Value) And IsNumeric(cell2.Value) Then
        Additionex = Evaluate(num1 + num2)
    Else
       Additionex = CVErr(xlna)
    End If
End Function

7 Comments

Could you shortly explain on this case the preference of ByVal.
What do I gain?
you are passing the actual value of an argument not a reference. The advantage of passing an argument ByVal is that it protects a variable from being changed by the procedure.
@VBasic2008 The same rule applies for objects, but ByVal and ByRef apply to the object reference itself. If you pass an object ByVal, the called procedure can't alter the object pointer (set it to a new object or set it to Nothing). It can still alter properties of the object.
|
0

Don't make it an array:

Function Additionex(num1 As Double, num2 As Double) As Double
    Dim num3 As Double
    num3 = num1 + num2
    Additionex = num3
End Function

enter image description here

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.