Hi,
I don't really understand how the code below (which I found on the net) works and I was hoping someone could help me out with some questions:
[vba]Sub CheckRanges()
Dim vNames As Variant, v As Variant
vNames = Array("ABC", "DEF", "GHI", "JKL", "MNO")
For Each v In vNames
Debug.Print v, RangeExists(CStr(v))
Next
End Sub
Function RangeExists(s As String) As Boolean
On Error GoTo Nope
RangeExists = Range(s).count > 0
Nope:
End Function[/vba]
I understand that the sub is setup to pass an array of strings to the function RangeExists and the results are printed to the immediate window. What I don't get is quite how it all works, so my questions:
1. Why do you need to use CStr when passing the variable 'v' to the RangeExists function? (given that each array item in 'v' is a string already)
2. How does this line in particular work:
RangeExists = Range(s).count > 0
In what order does that execute?
I thought if you used an assignment (variable = something) you couldn't use a comparison operator with out it being inside an if statement; so in pseudo code it would like this:
RangeExists = IF(Range(s).count > 0, True, False)
3. Is it poor practice not to explicitly code RangeExists = False at the start of the function?
4. Does anyone know of a better way to efficently check whether an explicitly defined named range exists?
That is to say, I want to test whether:
'NamedRange' (passed as a string), exist within 'Worksheet Object' (passed as worksheet object) within the named 'Workbook Object' (passed as a workbook object)...
So again in dodgy pseudo code -
Does:
WorkbookObject.WorksheetObject.Range(NamedRange)
exist within:
WorkbookObject.WorksheetObject
EDIT:
Also one further question, am I being redundant in how I address that range?
For instance is:
WorksheetObject.Range(NamedRange)
Exactly the same as:
WorkbookObject.WorksheetObject.Range(NamedRange)
for some reason? (say because the worksheet object already holds information about which workbook it is in?)
Cheers