Share via

Empty array in Word VBA

Anonymous
2016-12-27T12:02:28+00:00

My abbreviated code is as follows ...

Option Explicit

Option Base 1

Sub MyCode()

Dim c As Long

Dim strNumber as String

Dim arrNumerals As Variant 'An array to hold all numerals from within the document. Initial length unknown.

c = 1

With ActiveDocument.Content

With .Find

.ClearFormatting

.Text = "[0-9]"

.Replacement.Text = ""

.Forward = True

.Wrap = wdFindStop

.MatchWildcards = True

End With

While .Find.Execute

    strNumber = .Text    ' This works OK

    'MsgBox strNumber

    ReDim arrNumerals(c)

    arrNumerals(c) = .Text

    MsgBox arrNumerals(c)

    c = c + 1

    ReDim Preserve arrNumerals(c)

Wend

    .Find.MatchWildcards = False

End With

   MsgBox "Total numbers found = " & c

   MsgBox arrNumerals(1)   ' Returns null

   MsgBox arrNumerals(2)   ' Returns null 

End Sub

At the end of the routine, the array is empty.

Can anyone explain why?

Microsoft 365 and Office | Word | For home | Windows

Locked Question. This question was migrated from the Microsoft Support Community. You can vote on whether it's helpful, but you can't add comments or replies or follow the question.

0 comments No comments

Answer accepted by question author

Paul Edstein 82,861 Reputation points Volunteer Moderator
2016-12-27T12:50:54+00:00

At the end of the routine, the array is empty.

Can anyone explain why?

Because ReDim arrNumerals(c) clears the array. Try:

Sub MyCode()

Dim c As Long, arrNumerals() As Variant

With ActiveDocument.Content

  With .Find

    .ClearFormatting

    .Text = "[0-9]"

    .Replacement.Text = ""

    .Forward = True

    .Wrap = wdFindStop

    .MatchWildcards = True

  End With

  While .Find.Execute

    c = c + 1

    ReDim Preserve arrNumerals(c)

    arrNumerals(c) = .Text

  Wend

End With

MsgBox "Total numbers found = " & c & ":" & vbCr & Join(arrNumerals, ",")

End Sub

Was this answer helpful?

0 comments No comments

1 additional answer

Sort by: Most helpful
  1. Anonymous
    2016-12-27T13:35:32+00:00

    Many thanks.

    Was this answer helpful?

    0 comments No comments