在VBA for Excel中,如何将以下代码限制为仅在一个Tab中运行?

时间:2017-03-22 15:40:36

标签: excel vba excel-vba

我正在使用以下Excel VBA脚本:

Sub Multi_FindReplace()
'PURPOSE: Find & Replace a list of text/values throughout entire workbook
'SOURCE: www.TheSpreadsheetGuru.com/the-code-vault

Dim sht As Worksheet
Dim fndList As Variant
Dim rplcList As Variant
Dim x As Long

fndList = Array("Mostly satisfied", "Completely satisfied", "N/A", "Not at all satisfied")
rplcList = Array("Satisfied", "Satisfied", "Satisfied", "Not satisfied")


'Loop through each item in Array lists
  For x = LBound(fndList) To UBound(fndList)
    'Loop through each worksheet in ActiveWorkbook
      For Each sht In ActiveWorkbook.Worksheets
        sht.Cells.Replace What:=fndList(x), Replacement:=rplcList(x), _
          LookAt:=xlPart, SearchOrder:=xlByRows, MatchCase:=False, _
          SearchFormat:=False, ReplaceFormat:=False
      Next sht

  Next x

End Sub

但问题是它在我的工作表的所有3个选项卡上运行,当我只希望它在一个单独的选项卡上工作时 - 称为" Refined" 。

如何更改代码,使其仅循环于" Refined"标签 ?

我是否需要删除行Dim sht As Worksheet并将其转到:

Dim sht as "Refined1"

任何提示赞赏,谢谢

1 个答案:

答案 0 :(得分:3)

替换:

'Loop through each item in Array lists
For x = LBound(fndList) To UBound(fndList)

    'Loop through each worksheet in ActiveWorkbook
    For Each sht In ActiveWorkbook.Worksheets '<-- This line is looping through worksheets
        sht.Cells.Replace What:=fndList(x), Replacement:=rplcList(x), _
        LookAt:=xlPart, SearchOrder:=xlByRows, MatchCase:=False, _
        SearchFormat:=False, ReplaceFormat:=False
    Next sht

Next x

有了这个:

Set sht = ActiveWorkbook.Sheets("Refined1")

'Loop through each item in Array lists
For x = LBound(fndList) To UBound(fndList)

    sht.Cells.Replace What:=fndList(x), Replacement:=rplcList(x), _
    LookAt:=xlPart, SearchOrder:=xlByRows, MatchCase:=False, _
    SearchFormat:=False, ReplaceFormat:=False

Next x