VBA替换号码问题

时间:2016-05-17 17:06:10

标签: excel vba excel-vba

我有一个问题,我需要用贷款标识符替换一个号码,我遇到的问题是贷款标识符包含需要更换的号码,所以我最终得到类似" LOAN1592LOAN3161LOAN29269704932LOAN2926970411"当我真正想要的是,如果贷款号码是6,它将被替换为LOAN31617932而不是上述。有什么想法,我怎么能阻止这种情况发生?我希望这是有道理的。请查看我的代码段如下:

    Columns("e:e").Select
    Selection.Replace What:="5", Replacement:="LOAN15926711", LookAt:=xlPart, _
    SearchOrder:=xlByRows, MatchCase:=False, SearchFormat:=False, _
    ReplaceFormat:=False

     Columns("e:e").Select
    Selection.Replace What:="6", Replacement:="LOAN31617932", LookAt:=xlPart, _
    SearchOrder:=xlByRows, MatchCase:=False, SearchFormat:=False, _
    ReplaceFormat:=False

     Columns("e:e").Select
    Selection.Replace What:="7", Replacement:="LOAN29269704", LookAt:=xlPart, _
    SearchOrder:=xlByRows, MatchCase:=False, SearchFormat:=False, _
    ReplaceFormat:=False

     Columns("e:e").Select
    Selection.Replace What:="8", Replacement:="LOAN57538987", LookAt:=xlPart, _
    SearchOrder:=xlByRows, MatchCase:=False, SearchFormat:=False, _
    ReplaceFormat:=False

2 个答案:

答案 0 :(得分:2)

我改为If(或Select Case)。请参阅上面的评论,了解原因。这有用吗:

Sub t()
Dim cel As Range, rng As Range
Dim lastRow&

lastRow = Cells(Rows.Count, 5).End(xlUp).row

Set rng = Range("E1:E" & lastRow)
For Each cel In rng
    If InStr(1, cel.Value, "2") Then cel.Value = "LOAN15926711"
    If InStr(1, cel.Value, "6") Then cel.Value = "LOAN31617932"
    ' etc. etc.
Next cel
End Sub

如果单元格56等,那么就这样做

If cel.Value = "6" Then ...

Edit2:但我会听@GarysStudent,添加简单的xlWhole就是你想要的。简单,干净,简单。

答案 1 :(得分:2)

使用xlWhole

Sub luxation()
Columns("e:e").Replace What:="5", Replacement:="LOAN15926711", LookAt:=xlWhole, _
    SearchOrder:=xlByRows, MatchCase:=False, SearchFormat:=False, _
    ReplaceFormat:=False
End Sub

在:

enter image description here

之后:

enter image description here

注意:

55 555 会被忽略!