Reputation: 75
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?
Upvotes: 1
Views: 767
Reputation: 5543
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
Upvotes: 0
Reputation: 4099
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,
Upvotes: 1