在我的MS-Word模板中,我的客户端在标题部分发送错误的模板,如下所示,
VERMONT,ROBIN S.日期:10/21/2017 文件号:312335 DOB:05/02/1967Claim#:RE155B53452 DOI:06/21/2017
错误是'Claim#'出现在DOB值旁边,而它应该出现在下一行,如下所示:
VERMONT,ROBIN S.日期:10/21/2017 文件号:312335 DOB:05/02/1967 声明#:RE155B53452 DOI:06/21/2017
此外,这个错误偶尔出现在一些文件中而不是全部,所以为了解决它,我创建了一个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()时,对于所有出现此类错误的文件,它会将“Claim#”转移到下一行。
然而,问题是,对于没有这样问题的文件也会这样做,从而在DOB下方添加一条输入行,如下所示(如黄线所示):
我应该对我的宏ShiftClaimNumber2NextLine()进行哪些更改,以便它不会对 没有 “声明#”问题的文件进行任何更改?
答案 0 :(得分: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