I am curious to know about what is considered to be the best method to check for errors before running a function. Is it best to make a check before the function is called or within the function itself?
For example, a simplified version of what I'm working on involves this Click subroutine:
Private Sub MyButton1_Click()
For j = 1 to 3
CreateChart Sheets(j)
Next j
End Sub
Where the function it calls is defined like so:
Function CreateChart(Sht As Worksheet) As Boolean
Set ChtObj = Sht.ChartObjects.Add(40, 40, 600, 300)
Set Cht = ChtObj.Chart
...
End Function
I am dealing with code with multiple modules and many situations where certain checks need to be performed before the function can successfully run. Is it most appropriate to put a check within the loop in the Click sub routine, something like:
If DoesSheetExist(Sheets(j)) Then CreateChart(Sheets(j))
Or best to put it within the function like:
If Not DoesSheetExist(Sht) Then CreateChart = False: Exit Function
Currently I have a little bit of each practice scattered throughout the code and I would like to clean it up. Is it best to run this check outside the function or within?
Functioncode. It's simplier to maintain - e.g. if you'd like to change logic of your check, consider what would be the easiest: change logic in entire code or in single function?Booleanto sayIntegerand return1when there is no issue,-1when code fails on first check,-2- when code fails on second check and so on. And in your loop in main code you can add single msgbox for each error "code".