首页 > 解决方案 > 字符串处理参数

问题描述

Public Function GetAllUndershoreVaues() As Collection
On Error GoTo ErrorHandler
Dim colAux1 As Collection
Dim sentence As Range
Dim w As Words
For Each sentence In ActiveDocument.StoryRanges
    For Each w In sentence.Words
        If (InStr(w, "-") > 0) Then
            If Right(w, "-") Then
               colAux1.Add w, UCase$(w)
            Else
                Set colAux1 = Nothing
            End If
        Else
        Set colAux1 = Nothing
        End If
    Next
Next
    Set GetAllUndershoreVaues = colAux1
    Set colAux1 = Nothing
    Set sentence = Nothing
    Set w = Nothing
End Function

得到编译错误:

参数不是可选的

标签: vbams-word

解决方案


循环遍历每个故事范围中的每个单词是非常低效的。尝试以下方式:

Public Function GetAllUndershoreVaues() As Collection
Dim colAux1 As Collection, Rng As Range, StrItem As String
Set colAux1 = New Collection
For Each Rng In ActiveDocument.StoryRanges
  With Rng
    With .Find
      .ClearFormatting
      .Replacement.ClearFormatting
      .Text = "-*>"
      .Replacement.Text = ""
      .Forward = True
      .Format = False
      .Wrap = wdFindStop
      .MatchWildcards = True
    End With
    Do While .Find.Execute = True
      StrItem = Split(.Text, "-")(1)
      colAux1.Add StrItem, UCase$(StrItem)
      .Collapse (wdCollapseEnd)
    Loop
  End With
Next
Set GetAllUndershoreVaues = colAux1: Set colAux1 = Nothing
End Function

推荐阅读