Observation on post by JGM of 4 Dec 2003

G

Greg

JGM,

I was reading your post of 4 Dec 2003 on using arrays. You may already
be aware of this, but I noticed an error in your method for resizing
the array after you have performed a conditional check as elements were
added. I set up 5 bookmarks in a test document. Two bookmarkds
contained your condition "Test." They were the 3rd and 4th bookmarks
in the document. While your code below does resize the array to 2, the
data in these two positions is Null.

Dim i As Integer
Dim IncludedItems As Integer
Dim MyArrayTest() As String
Dim ItemCount As Integer
ItemCount = ActiveDocument.Bookmarks.Count
IncludedItems = 0
'Maximum possible
ReDim MyArrayTest(1 To ItemCount)
For i = 1 To ItemCount
If InStr(ActiveDocument.Bookmarks(i).Name, "Test") <> 0 Then
MyArrayTest(i) = "Bookmark " & i & " name: " & _
ActiveDocument.Bookmarks(i).Name
IncludedItems = IncludedItems + 1
End If
Next i
'Resize to actual maximum, use Preserve otherwise the array
'content will be flushed
ReDim Preserve MyArrayTest(1 To IncludedItems)

I have changed it around a little and added a readback so you can see
it work:

Sub LessonArray3()
Dim i As Integer
Dim IncludedItems As Integer
Dim MyArrayTest() As String
Dim ItemCount As Integer
ItemCount = ActiveDocument.Bookmarks.Count
IncludedItems = 0
'Maximum possible
ReDim MyArrayTest(1 To ItemCount)
For i = 1 To ItemCount
If InStr(ActiveDocument.Bookmarks(i).Name, "Test") <> 0 Then
IncludedItems = IncludedItems + 1
MyArrayTest(IncludedItems) = "Bookmark " & i & " name: " & _
ActiveDocument.Bookmarks(i).Name
End If
Next i
'Resize to the actual size. Use Preserve otherwise the array content
will be flushed
ReDim Preserve MyArrayTest(1 To IncludedItems)
'Now read back
For i = 1 To UBound(MyArrayTest)
MsgBox MyArrayTest(i)
Next i
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

Top