我使用 Excel VBA 和以下方法在 html 文件中搜索字符串,并在添加粗体标记后将其替换为相同的字符串。
FindAndReplace ("C:\xxx.htm", "hello world", "<b>hello world</b>")
Private Sub FindAndReplace(filePath As String, findWhat As String, replaceWith As String)
Dim nextFileNum As Long
Dim oldFileContents As String
Dim newFileContents As String
Dim textFileTypes() As String
Dim fileExtension As String
Dim sFileName As String
Dim iFileNum As Integer
Dim sBuf As String
Dim strFound As Integer
If Len(Dir(filePath)) = 0 Then
Exit Sub
End If
nextFileNum = FreeFile
Open filePath For Input As #nextFileNum
oldFileContents = Input$(LOF(nextFileNum), #nextFileNum)
Close #nextFileNum
newFileContents = Replace(oldFileContents, findWhat, replaceWith)
nextFileNum = FreeFile
Open filePath For Output As #nextFileNum
Print #nextFileNum, newFileContents
Close #nextFileNum
End Sub
我面临的问题是该函数不会;如果由于 html 源代码换行符而将其拆分,则找不到该字符串。
例如,如果代码是,则找到该字符串:
<p>hi hola hello world</p>
但如果代码为:
<p>hi hola hello
world</p>
是否有任何其他 VBA 方法可用于搜索和替换文本,或者可以将某些功能添加到上面的代码中,以便它忽略中间的换行符。