Excel VBA搜索长文本字符串的列并替换其中的字符

时间:2016-09-08 13:57:17

标签: excel vba

我查看了本网站上的所有示例和答案,并在下面提出了这个小程序。但是,它不是仅替换包含“802722AA”的两行,而是替换不包含该字符串的所有其他行。我不知道为什么会发生这种情况。任何帮助表示赞赏。

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列的文本文件。我不能发短信给它,我不能做任何花哨的公式,因为它提供给拒绝输入的专有程序。请注意,那里有一些AGF,如果它包含文本802722AA,我只希望它更改为AGN。

2 个答案:

答案 0 :(得分:1)

如果是我,这可能效率不高,我想我会像这样使用split函数

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

答案 1 :(得分:1)

对于列#34; A"中的数据使用第1行中的标题,您可以使用以下代码:

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