首页 > 解决方案 > 在特定列而不是整个工作表中查找和替换

问题描述

我有下面的代码,它从表中查找特定单词并将它们替换为也在表中的其他内容。

但是,它替换了整个工作表中的所有内容,我实际上只希望它在特定列上工作(D:D)

任何人都可以帮忙吗?

Dim sht As Worksheet
Dim fndList As Integer
Dim rplcList As Integer
Dim tbl As ListObject
Dim myArray As Variant
    'Create variable to point to your table


 Set tbl = Worksheets("Tables").ListObjects("Word")
        'Create an Array out of the Table's Data
  Set TempArray = tbl.DataBodyRange
  myArray = Application.Transpose(TempArray)
        'Designate Columns for Find/Replace data
  fndList = 1
  rplcList = 2
        'Loop through each item in Array lists
  For x = LBound(myArray, 1) To UBound(myArray, 2)
        'Loop through each worksheet in ActiveWorkbook (skip sheet with table in it)
      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

标签: vba

解决方案


目前,您告诉它替换整个工作表的每个单元格中的数据:

sht.Cells.Replace

如果您只想替换列 C 和 D 中的数据,请指定:

sht.Columns("C:D").Replace

推荐阅读