在文件中查找和替换带换行符的字符串

时间:2016-12-11 22:13:36

标签: html regex vba replace ms-word

您好我正在尝试将多个html文件中的字符串替换为此类

示例文本

示例文本

空格

示例文本

单词find和replace有一个字符限制,notepad ++也是如此。白色空间造成问题和 到目前为止,这个宏不起作用

Sub TEST()
'
' TEST Macro
'
'
 Dim oWordApp As Object, oWordDoc As Object, rngStory As Object
    Dim sFolder As String, strFilePattern As String
    Dim StrFileName As String, sFileName As String

'~~> Change this to the folder which has the files
sFolder = "C:\Users\user\Desktop\vbtest"
'~~> This is the extention you want to go in for
strFilePattern = "*.htm"

'~~> Establish an Word application object
On Error Resume Next
Set oWordApp = GetObject(, "Word.Application")

If Err.Number <> 0 Then
    Set oWordApp = CreateObject("Word.Application")
End If
Err.Clear
On Error GoTo 0

oWordApp.Visible = True

'~~> Loop through the folder to get the htm files
StrFileName = Dir$(sFolder & strFilePattern)
Do Until StrFileName = ""
    sFileName = sFolder & StrFileName

    '~~> Open the word doc
    Set oWordDoc = oWordApp.Documents.Open(sFileName)

    '~~> Do Find and Replace
    For Each rngStory In oWordDoc.StoryRanges
        With rngStory.Find
            .Text = "/(sample text)\n(sample text)\n(sample text)\n[\s].*(sample text)/"
            .Replacement.Text = "/(sample text2)\n(sample text2)\n(sample text2)\n[\s].*(sample text2)/"
            .Wrap = wdFindContinue
            .Execute Replace:=wdReplaceAll
        End With
    Next

    '~~> Close the file after saving
    oWordDoc.Close SaveChanges:=True

    '~~> Find next file
    StrFileName = Dir$()
Loop

'~~> Quit and clean up
oWordApp.Quit

Set oWordDoc = Nothing
Set oWordApp = Nothing
End Sub

刚尝试使用正则表达式工作

0 个答案:

没有答案