VBA+Excel. Code error (incompatible Byref argument type) in Function

Asked

Viewed 3,070 times

4

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 

Returns this error: Incompatible type of argument Byref. here: raiz1 = X1(a,b,c)

What am I doing wrong?

  • I made only the correction in your code, see the edition of the answer to notice your original code, with small redundancies that had left intentionally to visualize only what was wrong. Respecting the point of view of our colleague danieltakeshi and the community that approved the edition, the reply!

1 answer

2


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

Dim a, b, c, delta, raiz1, raiz2 As Double declares only raiz2 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’ve helped!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.