I am moderately experienced with Excel and VB (2003) but I am encountering issues when handling dynamic ranges for handling lists/tables. I have always found an ad hoc solution to these issues, depending on the application. However, I am wondering if there is a consensus of what is the best practice in these cases?
The issue arises when a dynamic range is defined for a list/table that during use may end up with zero length for one or both dimensions.
Consider a dynamic range for a list defined as follows:
=OFFSET(ListOrigin,0,0,COUNTA(OFFSET(ListOrigin,0,0,MaxListLength,1)),1)
Where:
ListOrigin is a defined name for the cell that is the origin of the list
MaxListLength is a defined name for a cell containing the maximum length of list (to avoid doing a COUNTA on a whole column)
There are two options I have used for ListOrigin, both of which present their own issues when subsequently handling the list in both Excel formulas and especially in VB.
If the list is defined to include the header, then it frequently has to be trimmed off before being handled.
eg
...
Dim rngList As Range
Set rngList =[ListWithHeader]
If rngList.Rows.Count > 1 Then
Set rngList = rngList.Resize(rngList.Rows.Count - 1)
Else
'Code to handle empty List
End If
'Rest of the code dealing with List
...
Display More
Sometimes it is not necessary to trim off the header and this seems very efficient, but consider a list who's heading is 'List' but ends up by a twist of fate containing an entry called 'List', all of a sudden your VLOOKUP produces unexpected results.
The alternative is to define ListOrigin for the first potential entry in the list. This avoids having to trim the header off for formulas and VB code. However if the list is empty then it turns the dynamic range into a #REF error. It is easy to create Excel formulas to handle but in VB it becomes quite troublesome.
eg
...
Dim rngList As Range
On Error GoTo ErrorHandler
Set rngList =[ListWithoutHeader]
' If we get here without throwing an error then List length >= 1
'Rest of the code dealing with List
...
ErrorHandler:
Select Case Err.Number
Case 424
'Code to handle empty List
Case Else
'Other error handling code
End Select
...
Display More
This solution can be clumsy particularly during development when the VB code may throw a 424 error for other reasons that you don't want handled as an empty List.
Perhaps someone out there has an altogether more elegant way of dealing with this whole issue that I have not considered, or simply can give advice as to what would be best practice in these situations?