Consider the following VBA function:
Function getFirstColumn(Optional sheetName As String) As Long
'In particular the IF statement below.
If sheetName = "" Or sheetName = Null Then sheetName = ActiveWorkbook.ActiveSheet.Name
With ActiveWorkbook.Worksheets(sheetName)
getFirstColumn = .Cells.Find("*", .Cells(1), xlFormulas, xlWhole, xlByColumns, xlNext).Column
If Err <> 0 Then getFirstColumn = 0
End With
End Function
When using this function, I don’t have problems when using it from a second opened sheet.
But when the code is changed to it’s function-based equivalent, 'If IsEmpty(sheetName) Or IsNull(sheetName) Then sheetName = ActiveWorkbook.ActiveSheet.Name, I get problems if I try to use the function from a sheet that doesn’t own it:
Erro em tempo de execução ‘9’:
Subscrito fora do intervalo.
What are the differences between them? And why is such error triggered exactly?
“sheetName” is a variable. The variable may be undefined, might refer to an object … or might be NULL.
If it’s an object, the object itself might evaluate to the variant value NULL. Hence the “IsNull()” function.
Other variants include “IsEmpty()” (which you mentioned), “IsNothing()” and even “IsMissing()”:
http://social.msdn.microsoft.com/Forums/en-US/accessdev/thread/aff30d44-0a7d-435e-8f15-7edd4f7f03d1/
http://www.tek-tips.com/faqs.cfm?fid=3710