替换字符串的所有实例,但第一个除外

时间:2020-07-16 21:29:27

标签: vba ms-word

我需要清理MS Word文件中的文本。

我从这样的Web表单接收文本,然后将其作为Word文件获取。

formatoptions

我想摆脱所有“已确认”,但对于第一个,要获得类似于以下内容。

" Do not auto-wrap comments and don't insert comments when pressing o/O. See: :h *fo-table* and :h *'formatoptions'*
set formatoptions-=cro
autocmd Filetype * set formatoptions-=cro

我算出所有单词

Confirmed: Something
Confirmed: Else
Confirmed: every
Confirmed: time

我找到了有关如何删除第一个或最后一个的文章,但不知道如何删除除第一个以外的所有内容。

2 个答案:

答案 0 :(得分:0)

尝试一下:

Sub tester()
    Dim col As Collection, i As Long
    
    Set col = AllOccurrences("Confirmed:")
    For i = 2 To col.Count
        col(i).Text = vbTab 'replace the text with a tab
    Next i

End Sub

'Return a collection with all instances of strToMatch in the activedocument
Function AllOccurrences(ByVal strToMatch As String) As Collection
    Dim rv As New Collection, rng As Range
    Set rng = ActiveDocument.Range
    With rng.Find
        .Text = strToMatch
        .Format = False
        .Wrap = wdFindStop
        Do While .Execute
            rv.Add ActiveDocument.Range(rng.Start, rng.End)
        Loop
    End With
    Set AllOccurrences = rv
End Function

答案 1 :(得分:0)

难道您只是替换了“ Confirmed:”的所有实例,并在开始时标记了一个新实例吗?

    Dim sMessage As String
    
    sMessage = "Confirmed: Something" & vbCrLf & _
               "Confirmed: Else" & vbCrLf & _
               "Confirmed: every" & vbCrLf & _
               "Confirmed: Time"
               
    Debug.Print "Confirmed:" & Replace(sMessage, "Confirmed:", "")
相关问题