1

I'm learning VBA and I'm having trouble returning a boolean value from one function to another. I've been seeing other similar questions to try to solve but I couldn't.

So, I have this function :

Public Function Verifica_Permite_Gas()      
    Dim permit As Boolean       

' Se a torneira permite gasta
    If Permite_GAS Then         
        permit = True           
    Else

' Não permite
        Debug.Print "Erro torneira nao devia conter Gas - Torneira_3 - metodo Permite_GAS"          
        permit = False

    End If

End Function

And you should return the value for this function

Public Function Verifica_Gas()      
    Dim permite As Boolean

    permite = listaTorneiraSetor(a).Verifica_Permite_Gas()

End Function

The program works, has no errors but always returns false even when Permit_GAS = TRUE I don't understand why, can someone help me solve it?

2 Answers 2

1

You need to modify your original function to return a value:

Public Function Verifica_Permite_Gas() As Boolean
    Dim permit As Boolean
' Se a torneira permite gasta
    If Permite_GAS Then
        permit = True
    Else
' Não permite
        Debug.Print "Erro torneira nao devia conter Gas - Torneira_3 - metodo Permite_GAS"
        permit = False
    End If
    Verifica_Permite_Gas=permit
End Function

And you could do without declaring and using permit by setting Verifica_Permite_Gas directly to be True or False within the If/Else/End If block:

If Permite_GAS Then
    Verifica_Permite_Gas= True
Else
    Verifica_Permite_Gas= False
End If

Regards,

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

Comments

0

Functions in VBA are a bit funny in that they have no return statement like in some other languages. The way to return a value from a function is to assign the value to the function's name.

So inside Verifica_Permite_Gas, you just need to make sure at some point you have Verifica_Permite_Gas = result

you can imagine every Function containing a Dim Verifica_Permite_Gas As ... somewhere in there where you need to write the result.

So just get rid of Dim permit As Boolean and instead use:

Public Function Verifica_Permite_Gas()

' Se a torneira permite gasta
If Permite_GAS Then

    Verifica_Permite_Gas = True

Else
    ' Não permite
    Debug.Print "Erro torneira nao devia conter Gas - Torneira_3 - metodo Permite_GAS"

    Verifica_Permite_Gas = False

End If

End Function

Also remember that you declared permit As Boolean - well you can do the same with your function return value so it is

Public Function Verifica_Permite_Gas() As Boolean

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.