Excel VBAsearch长文本string的列并replace其中的字符

我已经看过这个网站上的所有例子和答案,并在下面提出了这个小程序。 但是,不是只replace包含“802722AA”的两行,而是replace不包含string的其他所有内容。 至于为什么会发生这种情况,我不知道。 任何帮助表示赞赏。

Sub FindAndReplaceAGF() Dim Loc As Range Dim RowNum As Integer Dim LastRow As Long With Sheets(2).UsedRange Range("A1").Select Set Loc = .Cells.Find(What:="802722AA") If Not Loc Is Nothing Then Do Loc.EntireRow.Select Selection.Replace What:="AGF", Replacement:="AGN", LookAt:=xlPart, _ SearchOrder:=xlByRows, MatchCase:=False, SearchFormat:=False, _ ReplaceFormat:=False RowNum = Loc.Row Set Loc = .FindNext(Loc) Loop While Loc.Row > RowNum End If End With Set Loc = Nothing 

我的数据看起来像这样,我只是编辑它,因为它是一个400多行的列表。

 802722AA SANTA ROSA LEASING LLC2 AGF 59511VAA MICRON SEMICONDUCTOR AGF 973204AA WINDERMERE AVIATION LLC AGY 92242VAB VCK LEASE SA AGF 68839PAB OSPREY AIRCRAFT LEASING AGF 79977TAC SANDALWOOD 2013 LLC AGN 02154QAA ALTITUDE INVEST 16 LLC AGF 802722AA SANTA ROSA LEASING LLC AGF 45170$88 ILLINOIS FACILITIES FUND ACM 

请注意,这是一个文本文件,全部转储到Excel中的列A中。 我无法将文字列出来,也无法做任何奇特的公式,因为它会传送给专有程序,拒绝input。 请注意,这里有一些AGF,如果它包含文本802722AA,我只希望将其更改为AGN。

对于列1中列标题为“A”的数据,您可以使用以下代码:

 Option Explicit Sub Main() With Worksheets("MySheetName") With .Range("A1", .Cells(.Rows.Count,1).End(xlUp)) .Autofilter field:=1, Criteria1:="802722*" If Application.WorksheetFunction.Subtotal(103, .Cells) > 1 Then . Replace "AGF", "AGN" End With .AutoFilterMode = False End With End With 

如果是我,这可能不是那么高效,我想我会利用这样的splitfunction

 finalRow = cells(65000,1).end(xlup).row 'get the last row of column A for i=2 to finalRow parts = split(cells(i,1), " ") 'make an array out of the parts separated by spaces newString = "" if parts(0) = "802722AA" and parts(ubound(parts))="AGF" then for j=lbound(parts) to ubound(parts) - 1 'get all but the last part newString = newString & " " & parts(j) 'make a new string of all but the last part next j newString = newString & " AGN" 'at the end, replace the AGF with AGN end if cells(i,1)=newString 'replace contents of cell with our newly constructed string next i