使用VBA查找和替换文本

使用VBA查找和替换文本,vba,replace,Vba,Replace,我使用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

我使用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
FindAndReplace(“C:\xxx.htm”、“你好世界”、“你好世界”)
私有子FindAndReplace(文件路径为字符串,findWhat为字符串,replaceWith为字符串)
Dim nextFileNum尽可能长
将oldFileContents设置为字符串
将newFileContents设置为字符串
Dim textFileTypes()作为字符串
将文件扩展名设置为字符串
将sFileName设置为字符串
作为整数的Dim iFileNum
作为字符串的Dim sBuf
作为整数的Dim strFound
如果Len(Dir(filePath))=0,则
出口接头
如果结束
nextFileNum=FreeFile
以#nextFileNum的形式打开输入的文件路径
oldFileContents=Input$(LOF(nextFileNum),#nextFileNum)
关闭#下一个文件
newFileContents=Replace(oldFileContents、findWhat、replaceWith)
nextFileNum=FreeFile
打开输出为#nextFileNum的文件路径
打印#下一个文件名,新文件内容
关闭#下一个文件
端接头
我面临的问题是功能赢得;如果由于html源代码换行符而在字符串之间拆分,则无法找到该字符串

例如,如果代码为:

<p>hi hola hello world</p>
<p>hi hola hello 
world</p>
你好,你好,世界你好

但如果代码为:

<p>hi hola hello world</p>
<p>hi hola hello 
world</p>
你好,你好,你好 世界


是否有其他VBA方法可以用于搜索和替换文本,或者可以在上述代码中添加一些功能,以便忽略中间的换行符

尝试使用以下变量:

Function RemoveCarriageReturns(SourceString As String) As String

    Dim s As String

    'strip out CR and LF characters together
    s = Replace(SourceString, vbCrLf, "")

    'just in case, remove them one at a time
    s = Replace(s, Chr(13), "")
    s = Replace(s, Chr(10), "")

    RemoveCarriageReturns = s

End Function

ASCII字符13和10是回车符和换行符。

如果拆分仅使用换行符/换行符(
Chr(10)
Chr(13)
)和/或空格
Chr(32)
,则可以先搜索“hello”

找到后,查找这些字符(10、13和32)并跳过它们,直到遇到其他字符(使用
DO WHILE…或…或…或
循环)

现在检查是否有其他字符是“world”,并且至少遇到了其中的一个字符


在这种情况下,您会将
“hello”
更改为
“hello”
,将
“world”
更改为
“world”

这会影响文件保存时的原始html代码吗?是,当您将字符串写回文件并保存时,您将从.htm文件中删除所有回车符和换行符。通过添加标记,您仍然会影响原始文件