• Hi All

    Please note that at the Chandoo.org Forums there is Zero Tolerance to Spam

    Post Spam and you Will Be Deleted as a User

    Hui...

  • When starting a new post, to receive a quicker and more targeted answer, Please include a sample file in the initial post.

Use of Boolean and Separate Functions:

Abhijeet R. Joshi

Active Member
Hi all,

Can you all please help me understand the use of the Boolean feature and the need of separate "Function" in VBA?
Also it would be of great help if you can help me with the Syntax that can be used in the above two..

Note: This is just for my learnings and not URGENT..:)
 
Boolean [True/False] can be used as some testing / conditional flag. In most of the short / example codes posted in the forum, chances are that it will be very rarely used.

Functions can be used to work as UDF [of which I am sure you've seen many examples]or can be built to handle the recursive code in the program.

Lets take an example where both these features can be used.

You have built up a program where you insert a sheet and assign a specific name but obviously you have to check if this sheet exists beforehand. And this you need to check at 10 different places in the code. So what do you do? Write it 10 times. Then one day you discover a bug in the code so what do you do? You have to fix it at 10 places.

In such cases, functions can prove useful. Function would be something like this:
Code:
Public Function blSheetExists(shtName As String) As Boolean
Dim wS As Worksheet
    On Error Resume Next
    Set wS = Sheets(shtName)
    If Not wS Is Nothing Then
        blSheetExists = True
    End If
    On Error GoTo 0
End Function

And the main code could be like [you can do this without bl variable directly but this is example]:
Code:
Sub MainCode()
    Dim bl As Boolean
    
    bl = blSheetExists("Sheet1")
    
    If bl Then
        MsgBox "Sheet Exists!"
    Else
        MsgBox "Sheet doesn't exist!"
    End If

End Sub
 
Back
Top