Debug.Assert

The Debug.Assert statement, also known as the Assert Statement can be used while writing or debugging code.
This is not to be confused with the Debug.Print statement.

Debug.Assert 

This statement can be used to evaluate a condition to be either True or False.
We can use assertion statements to help us identify errors in our code when we are debugging.
If an assertion evaluates to False then code execution will stop at that line.
Any Debug.Assert statements in your code will not affect the speed of execution and can be left in when code is distributed.
link - excelmacromastery.com/vba-assert/


Example

Assert statements are often used for the following:
*) Checking the values passed in to subroutines or functions
*) Checking a value before it is returned from a function
*) Checking the value of global variables
This example checks the values passed in and the value before it is returned from a function

Public Sub Testing() 
   Debug.Print CheckValues(5)
   Debug.Print CheckValues(21)
   Debug.Print CheckValues(15)
End Sub

Public Function CheckValues(ByVal iValue As Integer) As String
Dim sReturn As String
   Debug.Assert iValue > 0 And iValue < 20
   sReturn = VBA.Space(iValue)
   Debug.Assert VBA.Len(sReturn) < 10
   CheckValues = "Success"
End Function

Error Handling

Assertions can only be used to test conditions that are internal to your code.
Assertions should be used in addition to Error Handling not as a substitute.
Assertions provide a way of adding Conditional Breakpoints to your code.
Assertions will stop execution and the program state will enter a debugging state (exactly the same as a breakpoint).
Assertions only work when the VBA Project is not password protected.


Turning On and Off

Once you code is ready to be released you can switch off the assertions by using a Compilation Constant
Add the following declaration at the top of the code module "debug = 1".

#Const g_Conditional = 1 

Lets add the conditional compiled blocks to our code

Public Sub Testing() 
   Debug.Print CheckValues(5) 'Success
   Debug.Print CheckValues(21) 'Execution stops
   Debug.Print CheckValues(15) 'Execution stops
End Sub

Public Function CheckValues(ByVal iValue As Integer) As String
Dim sReturn As String
   #If g_Conditional = 1 Then
      Debug.Assert iValue > 0 And iValue < 20
   #End If
   sReturn = VBA.Space(iValue)
   #If g_Conditional = 1 Then
      Debug.Assert VBA.Len(sReturn) < 10
   #End If
   CheckValues = "Success"
End Function

© 2021 Better Solutions Limited. All Rights Reserved. © 2021 Better Solutions Limited TopPrevNext