Detect if dynamic array has been initialised?

  • Thread starter Thread starter Dave Ramage
  • Start date Start date
D

Dave Ramage

Here is a bit of code that hopefully demos what I'm after:

Dim strDemo() as String

Sub SUBA()
If MsgBox("Initialise?", vbYesNo) = vbYes then
ReDim strDemo(1)
strDemo(0) = "a"
strDemo(1) = "b"
End if
End Sub

Sub SUBB
If [has strDemo been initialised?] then
'do something
Else
'do something else
End If
End Sub

Question:
How can I check whether the dynamic array strDemo has been
ReDim'ed within SUBA? IsArray and Ubound seem to cause an
error if used with a non-initialised array. I guess I
could use error trapping as the answer but this seems a
bit clumsy!

Thanks for any help people can give...

Cheers,
Dave
 
Dave,

Use the error:

Sub SUBA()
If MsgBox("Initialise?", vbYesNo) = vbYes Then
ReDim strDemo(1)
strDemo(0) = "a"
strDemo(1) = "b"
End If
End Sub

Sub SUBB()
Dim myBound As Integer
On Error GoTo notInit
myBound = UBound(strDemo)
MsgBox "Initialized"
Exit Sub
notInit:
MsgBox "Not initialized"
End Sub

HTH,
Bernie
MS Excel MVP
 
Dave,
I think error trapping is the way. Use of error trapping in this way is an
inherent part of the design of VBA, so while it might seem clumsy or
inelegant, I think we have to accept that that is the design of the
language.

Isarray worked fine for me whether the array had been redim'd or not.
Ubound (or lbound) was an indicator

Sub Subb()
Dim lb As Variant
lb = cvErr(xlErrValue)
on error Resume Next
lb =ubound(strDemo)
On Error goto o
if iserror(lb) then
msgbox "Not initialized"
else
msgbox "Upperbound is " & lb
End if
End Sub
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Back
Top