查找并替换字符串问题

时间:2018-03-22 20:45:01

标签: excel vba excel-vba

我有一些产品信息,我需要使用vba代码更新主代码。我的产品代码类似于 0001-11-22 主码为 0001 的所有数字,前4位数字。我想替换一些主代码,所以当我做sumifs函数时,它正在正确计算。

因此,主代码为0046,0548,0540和0545的产品需要相应地替换为0152,0438,0041和0041。含义0046需要由0152替换,0540和& 0545需要替换0545。

我在网上进行了一些研究并修改了符合我条件的代码,但有两个问题。 1)似乎它正在替换包含搜索字符串值的每个单元格,2)它将值替换为41而不是0041.下面的图片显示了我提到的两个问题。所以0041-00-00最初有0545-00-00,我不想更新。我只想更新主代码列。

Sub test()

Dim ws99 As Worksheet
Dim LR99 As Long

Set ws99 = Worksheets("raw data")
LR99 = ws99.Range("A" & Rows.Count).End(xlUp).Row

ws99.Activate



     'Master code
     ws99.Range("AH1") = "Master Code"
     With ws99.Range("AH2", "AH" & LR99)
     .FormulaR1C1 = "=LEFT(RC[-26], 4)"
     End With

    'All values
   ws99.Range("AH:AH").Select
   Selection.Copy
   Selection.PasteSpecial Paste:=xlPasteValues

   Dim v As Integer
v = Val(ws99.Range("AH2", "AH" & LR99))
Dim cid As String
cid = Format(v, "00")


Dim fndList As Variant
Dim rplcList As Variant
Dim x As Long

fndList = Array("0046", "0548", "0540", "0545")
rplcList = Array("0152", "0438", "0041", "0041")


  For x = LBound(fndList) To UBound(fndList)
          ws99.Columns("AH:AH").Replace What:=fndList(x), Replacement:=rplcList(x), _
          LookAt:=xlWhole, SearchOrder:=xlByRows, MatchCase:=False, _
          SearchFormat:=False, ReplaceFormat:=False

  Next x


End Sub

enter image description here

1 个答案:

答案 0 :(得分:1)

我会选择像

这样的东西
ws99.Range("AH:AH").NumberFormat = "@"

For x = LBound(fndList) To UBound(fndList)
    for i = 2 to LR99
        if ws99.Range("AH" & i).Value = fndList(x) then
            ws99.Range("AH" & i).Value = rplcList(x)
        end if
    next i
next x

查找方法经常会出现问题

实际上要明确你不需要所有的代码......我会改变它像

Sub test()

    Dim ws99 As Worksheet
    Dim LR99 As Long, x As Long, i a Long
    Dim fndList As Variant, rplcList As Variant

    Set ws99 = Worksheets("raw data")
    LR99 = ws99.Range("A" & Rows.Count).End(xlUp).Row

    fndList = Array("0046", "0548", "0540", "0545")
    rplcList = Array("0152", "0438", "0041", "0041")
    ws99.Range("AH:AH").NumberFormat = "@"

    For x = LBound(fndList) To UBound(fndList)
        For i = 2 to LR99
            If Left(ws99.Range("H" & i).Value, 4) = fndList(x) Then
                ws99.Range("AH" & i).Value = rplcList(x)
            End If
        Next i
    Next x

End Sub