2017-10-29 347 views
0

在我的MS-Word模板,我的客戶端發送模板與頭部段錯誤,如下面,文本替換

佛蒙特州,ROBIN S.日期:2017年10月21日 文件編號: 312335出生日期:05/02/1967Claim#:RE155B53452 DOI:06/21/2017

錯誤是'Claim#'出現在DOB值的旁邊,而它應該出現在下一行,如下:

VERMONT,ROBIN S.日期:10/21/2017 文件編號:312335出生日期:05/02/1967 索賠號: RE155B53452 DOI:2017年6月21日

而且,這個錯誤偶爾出現在一些文件,而不是全部,所以要解決這個問題,我創建了一個Word宏,如下:

Sub ShiftClaimNumber2NextLine() 

    Dim rngStory As Word.Range 
    Dim lngJunk As Long 
    'Fix the skipped blank Header/Footer problem as provided by Peter Hewett 
    lngJunk = ActiveDocument.Sections(1).Headers(1).Range.StoryType 
    'Iterate through all story types in the current document 
    For Each rngStory In ActiveDocument.StoryRanges 
    'Iterate through all linked stories 
    Do 
     With rngStory.Find 
     .text = "Claim#:" 
     .Replacement.text = "^pClaim#:" 
     .Wrap = wdFindContinue 
     .Execute Replace:=wdReplaceAll 
     End With 
     'Get next linked story (if any) 
     Set rngStory = rngStory.NextStoryRange 
    Loop Until rngStory Is Nothing 
    Next 

End Sub 

我跑上面的宏通過組宏,如下:

Sub ProcessAllDocumentsInFolder() 

Dim file 
Dim path As String 

' Path to folder 
path = "D:\Test\" 
file = Dir(path & "*.doc") 
Do While file <> "" 
Documents.Open FileName:=path & file 

' Call the macro to run on each file in the folder 
Call ShiftClaimNumber2NextLine 

' Saves the file 
ActiveDocument.Save 
ActiveDocument.Close 

' set file to next in Dir 
file = Dir() 
Loop 

End Sub 

當運行宏ProcessAllDocumentsInFolder(),用於與這樣的錯誤中的所有文件,它改變了「權利要求#」到下一行。

然而,問題是,它也確實所以沒有這樣的問題的文件,從而增加一個輸入線DOB下方,如下(按黃線如圖所示):

enter image description here

我應當怎​​樣更改我的宏ShiftClaimNumber2NextLine(),所以它不會進行任何更改文件,這DO NOT HAVE的「聲明#」的問題?

回答

0

這是最適合於正則表達式的情況見下面的鏈接,類似的問題,請參閱VBA解決方案

https://superuser.com/questions/846646/is-there-a-way-to-search-for-a-pattern-in-a-ms-word-document

Sub RegexReplace() 

    Dim RegEx As Object 
    Set RegEx = CreateObject("VBScript.RegExp")  
    On Error Resume Next 

    RegEx.Global = True 
    RegEx.Pattern = "[0-9]Claim#:" 
    ActiveDocument.Range = _ 
    RegEx.Replace(ActiveDocument.Range, "\rClaim#:")   

End Sub 
+0

謝謝。但不工作。 – vicki