查找和替换单元格中的值

Find and Replace values in cells

提问人:TheIronKing 提问时间:11/2/2022 最后编辑:CommunityTheIronKing 更新时间:1/31/2023 访问量:60

问:

我有一个产品代码电子表格。我需要改变其中的大约 200 个。

下面的代码删除了另一张工作表上单元格中的所有数据,而不是将其替换为第二列中的新产品代码。

Sub Multi_FindReplace()

    Dim sht As Worksheet
    Dim fndList As Integer
    Dim rplcList As Integer
    Dim tbl As ListObject
    Dim myArray As Variant

    Set tbl = Worksheets("Sheet4").ListObjects("Table1")

    Set TempArray = tbl.DataBodyRange
    myArray = Application.Transpose(TempArray)
  
    fndList = 1
    rplcList = 2

    For x = LBound(myArray, 1) To UBound(myArray, 2)
        For Each sht In ActiveWorkbook.Worksheets
            If sht.Name <> tbl.Parent.Name Then
          
                sht.Cells.Replace What:=myArray(fndList, x), Replacement:=myArray(rplcList, x), _
                  LookAt:=xlPart, SearchOrder:=xlByRows, MatchCase:=False, _
                  SearchFormat:=False, ReplaceFormat:=False
        
            End If
        Next sht
    Next x

End Sub
Excel VBA

评论

1赞 Tim Williams 11/2/2022
为什么要转置数组?这看起来很奇怪 - 通常你会遍历 2D 数组的单个维度......For x = LBound(myArray, 1) To UBound(myArray, 2)
0赞 TheIronKing 11/2/2022
嗨,蒂姆。我不能夸大我是一个新手。我一直在按照在线教程将其放在一起,所以作为答案,我不确定。我将如何更改它以遍历 2D 数组的单个维度?

答:

4赞 Tim Williams 11/2/2022 #1

试试这个:

Sub Multi_FindReplace()

    Dim sht As Worksheet, wb As Workbook, x As Long
    Dim fnd As String, rplc As String, tbl As ListObject, data As Variant

    Set wb = ActiveWorkbook
    Set tbl = wb.Worksheets("Sheet4").ListObjects("Table1")
    data = tbl.DataBodyRange.Value 'no need to transpose
    
    For x = LBound(data, 1) To UBound(data, 1) 'loop over data rows
        fnd = data(x, 1)                       'find value
        rplc = data(x, 2)                      'replace value
        If Len(fnd) > 0 And Len(rplc) > 0 Then 'make sure there are a pair of values
            For Each sht In wb.Worksheets
                If sht.Name <> tbl.Parent.Name Then
                  
                  sht.Cells.Replace What:=fnd, Replacement:=rplc, _
                      LookAt:=xlPart, SearchOrder:=xlByRows, MatchCase:=False, _
                      SearchFormat:=False, ReplaceFormat:=False
                
                End If
            Next sht
        End If           'have a pair of values
    Next x

End Sub

评论

0赞 TheIronKing 11/2/2022
这太不可思议了,第一次工作得很完美,非常感谢蒂姆。了不起。
0赞 Mayukh Bhattacharya 11/2/2022
Tim Sir,您有工作文件的副本吗?你能分享一个onedrive链接吗?
0赞 Tim Williams 11/2/2022
我没有工作文件 - 我刚刚编辑了发布的代码。不过,只有一个 Sub - 您可以轻松地将其添加到任何文件中并试用。
0赞 Mayukh Bhattacharya 11/2/2022
好的,先生,明白了,先生。