VBA + Excel. Error in code (Incompatible argument type Byref) in Function

2

The following code:

Sub segundograu()
Dim a, b, c, delta, raiz1, raiz2 As Double
a = Range("B3").Value
b = Range("E3").Value
c = Range("H3").Value
delta = b ^ 2 - 4 * a * c
Range("E5").Value = delta
If delta >= 0 Then
raiz1 = x1(a, b, c)
Range("C5").Value = x1

End If

End Sub

Function x1(a1 As Double, b1 As Double, c1 As Double) As Double
x1 = (-b + System.Math.Sqr(delta)) / 2 * a
End Function 

Return this error :  Incompatible type of Byref argument.  here: root1 = x1 (a, b, c)

What am I doing wrong?

    
asked by anonymous 30.09.2017 / 11:56

1 answer

1

To correct this error, simply use ByVal in the declaration of variables in your function, but there are two other points that I think you need to fix in your code, follow the corrections:

Dim a, b, c, delta, root1, root2 Double declares only root2 as Double and the others as Variant. The correct and best is Dim a as Long, b As Long, ... , n As Long

Sub segundograu()
Dim a As Long, b As Long, c As Long, delta As Long, raiz1 As Long, raiz2 As Long
    a = Range("B3").Value
    b = Range("E3").Value
    c = Range("H3").Value

    delta = b ^ 2 - 4 * a * c
        If delta > 0 Then
            raiz1 = x1(a, b, c)
            raiz2 = x2(a, b, c)
            Range("C5").Value = raiz1
            Range("C6").Value = raiz2
        ElseIf delta = 0 Then
            raiz1 = x1(a, b, c)
            Range("C5").Value = raiz1
            Range("C6").Value = ""
        ElseIf delta < 0 Then
            Range("C5").Value = "delta <0"
        End If
End Sub

' Coloque ByVal antes das variáveis para receber o valor e não a "referência"
Function x1(ByVal a1 As Long, ByVal b1 As Long, ByVal c1 As Long) As Long
    ' Para usar a função Sqr basta uscar "Sqr"
    delta = b1 ^ 2 - 4 * a1 * c1
    x1 = (-b1 + Sqr(delta)) / (2 * a1)
End Function
Function x2(ByVal a2 As Long, ByVal b2 As Long, ByVal c2 As Long) As Long
    delta = b2 ^ 2 - 4 * a2 * c2
    x2 = (-b2 - Sqr(delta)) / (2 * a2)
End Function

I hope I have helped!

    
30.09.2017 / 14:26