VBA搜索字符串和替换

时间:2014-08-19 17:04:45

标签: excel vba excel-vba

我们假设我们有一个名为text.txt的文本文件。在这个文本文件中有两行感兴趣。

src="somethingrandom1111.png"
src="morerandomnumberstuffthisnamewillvary.png"

我想要做的是搜索整个文档src ="然后用其他字符串替换之后的所有字符串,直到另一个字符串为止#34;找到了。所以,

src="somethingrandom1111.png"
src="morerandomnumberstuffthisnamewillvary.png"

会变成

src="thiswasreplace.gif"
src="thistoo!.jpg"

这是我的代码的一部分:

TempFile = Environ$("temp") & "\" & "index.htm"
With TempWB.PublishObjects.Add( _
     SourceType:=xlSourceRange, _
     Filename:=TempFile, _
     Sheet:=TempWB.Sheets(1).Name, _
     Source:=TempWB.Sheets(1).UsedRange.Address, _
     HtmlType:=xlHtmlStatic)
    .Publish (True)
End With
Set fso = CreateObject("Scripting.FileSystemObject")
Set ts = fso.GetFile(TempFile).OpenAsTextStream(1, 0)
ts = Replace(ts, 'src="', something)
ts.Close

2 个答案:

答案 0 :(得分:1)

一两个问题 - 替换字符串上的动作,而不是像在日常工作中那样替换文本流对象 - 此外,看起来好像您要搜索多个字符串,并为每个字符串添加不同的替换值。

以下代码显示了一种方法。我使用早期绑定和VBscript正则表达式引擎来进行替换。我将“查找字符串/替换字符串”存储在硬编码数组中以便于访问。我使用OpenTextFile方法而不是GetFile,但没有特别的原因。

您应该能够适应您的要求:

Option Explicit
Option Base 0
Sub FindReplaceInFile()
    Const sPath = "C:\users\ron\desktop\"
    Const sFN As String = "Text.txt"
    Dim FSO As FileSystemObject
    Dim TS As TextStream
    Dim S As String
    Dim arrFindReplace() As Variant
    Dim RE As RegExp
    Dim I As Long
    Dim sPat As String, sRepl As String

arrFindReplace = Array(Array("somethingrandom1111.png", "thiswasreplace.gif"), _
        Array("morerandomnumberstuffthisnamewillvary.png", "thistoo!.jpg"))

Set FSO = New FileSystemObject
Set TS = FSO.OpenTextFile(sPath & sFN, ForReading)
S = TS.ReadAll
TS.Close

Set RE = New RegExp
With RE
    .Global = True
    .IgnoreCase = True
End With

For I = 0 To UBound(arrFindReplace)
    sPat = "(src="")" & arrFindReplace(I)(0) & """"
    sRepl = "$1""" & arrFindReplace(I)(1) & """"
    With RE
        .Pattern = sPat
        S = .Replace(S, sRepl)
    End With
Next I

Set TS = FSO.OpenTextFile(sPath & sFN, ForWriting)
TS.Write S
TS.Close

End Sub

答案 1 :(得分:1)

您需要使用正则表达式。在Excel Visual Studio中激活正则表达式引擎。按照步骤

  1. 启动Microsoft Visual Basic Studio。

  2. 在“文件”菜单上,单击“新建项目”。

  3. 在“新建项目”对话框中单击“标准Exe”,然后单击“确定”。

  4. 在“项目”菜单上,单击“引用”。

  5. 双击“Microsoft VBScript Regular Expressions 5.5”,然后单击“确定”。

  6. 这是代码

    Sub RegEx_Macro()
    TempFile = Environ$("temp") & "\" & "index.htm"
    With TempWB.PublishObjects.Add( _
         SourceType:=xlSourceRange, _
         Filename:=TempFile, _
         Sheet:=TempWB.Sheets(1).Name, _
         Source:=TempWB.Sheets(1).UsedRange.Address, _
         HtmlType:=xlHtmlStatic)
        .Publish (True)
    End With
    
    Set fso = CreateObject("Scripting.FileSystemObject")
    Set ts = fso.OpenTextFile(TempFile, 1)
    strdata = ts.ReadAll
    
    Dim objRegExp As RegExp
       Dim objMatch As Match
       Dim colMatches   As MatchCollection
       Dim RetStr As String
       ' Create a regular expression object.
       Set objRegExp = New RegExp
    
       'Set the pattern by using the Pattern property.
       objRegExp.Pattern = "src="".*?"""
    
       ' Set Case Insensitivity
       objRegExp.IgnoreCase = True
    
       'Set global applicability.
    
       objRegExp.Global = True
       Set colMatches = objRegExp.Execute(strdata)  ' Execute search.
    
        For Each objMatch In colMatches ' Iterate Matches collection.
                strtoreplace = InputBox("Enter string to be replaced" , "Enter Replacement String For"& VbCrLf & objMatch.Value ) 'Give string to be replaced in inputbox
                strdata = Replace(strdata, objMatch.Value, strtoreplace)
        Next
        'ts.Close
        Set ts = fso.OpenTextFile(TempFile, 2)
        ts.Write strdata
        ts.Close
    
    End Sub
    

    希望这有助于!!