Vba 在数组中查找结果

Vba 在数组中查找结果,vba,ms-word,Vba,Ms Word,如何在数组中存储.查找结果 此宏使用通配符查找出现在sm>到fin> Selection.Find.ClearFormatting With Selection.Find .Text = "<sm&gt?<fin&gt" .Forward = True .Wrap = wdFindContinue .Format = False .MatchCase = False .MatchWholeWord

如何在数组中存储.查找结果

此宏使用通配符查找出现在
sm>
fin>

Selection.Find.ClearFormatting
With Selection.Find
    .Text = "<sm&gt?<fin&gt"
    .Forward = True
    .Wrap = wdFindContinue
    .Format = False
    .MatchCase = False
    .MatchWholeWord = False
    .MatchKashida = False
    .MatchDiacritics = False
    .MatchAlefHamza = False
    .MatchControl = False
    .MatchWildcards = True
    .MatchSoundsLike = False
    .MatchAllWordForms = False

End With
这部分统计文本中存在多少个
sm>
,以定义数组长度:

    Dim I As Long
    Dim J As Long
    Dim NumSm As Long
    Dim TargetText As String
    TargetText = "<sm&gt"
    J = 1
    I = 1
    While I > 0
    I = InStr(J, ActiveDocument.Range.Text, TargetText)
    If I > 0 Then
    NumSm = NumSm + 1
    J = I + 1
    End If
    Wend

    Dim SmArr() As Variant
    ReDim SmArr(0 To NumSm)

我想将查找结果存储在一个数组中:
SmArr()

您的问题有点难以理解,但我会尽我所能。您是否考虑过使用集合来代替?对于集合,您不必担心定义数组长度

Dim newColl as new collection
我将使用一个键向集合中添加项,这样您仍然可以像使用数组一样选择要读取的数据

newColl.add I, NumSm
NumSm是检索项目的密钥:

newColl.item X
或者只是迭代一个集合

Dim collObj as object

for each collObj in newColl
'stuff
next collObj

尝试以下几点:

Sub Demo()
Dim i As Long, SmArr()
With ActiveDocument.Range
  With .Find
    .ClearFormatting
    .Replacement.ClearFormatting
    .Text = "<sm&gt*<fin&gt"
    .Replacement.Text = ""
    .Forward = True
    .Wrap = wdFindStop
    .Format = False
    .MatchWildcards = True
    .Execute
  End With
  Do While .Find.Found
    i = i + 1
    ReDim Preserve SmArr(i)
    SmArr(i) = Split(Split(.Text, "<fin&gt")(0), "<sm&gt")(1)
    .Collapse wdCollapseEnd
    .Find.Execute
  Loop
End With
For i = 1 To UBound(SmArr)
  MsgBox SmArr(i)
Next
End Sub