我想知道如何运行 vba 脚本来查找和替换仅在一张工作表中而不是整个工作组中的多个单词?

Posted

技术标签:

【中文标题】我想知道如何运行 vba 脚本来查找和替换仅在一张工作表中而不是整个工作组中的多个单词?【英文标题】:I would like to know how to run a vba script to find and replace multiple words in only one sheet not the whole workgroup? 【发布时间】:2019-01-24 19:08:21 【问题描述】:

我找到了一个 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("United States", "New York")
rplcList = Array("US", "NY")

'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

【问题讨论】:

【参考方案1】:

只需删除工作表循环并在代码中显示“Sheet1”的位置指定工作表名称。

Sub Multi_FindReplace()

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

fndList = Array("United States", "New York")
rplcList = Array("US", "NY")
Set sht = ActiveWorkbook.Worksheets("Sheet1")   'this is the relevant worksheet    
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

End Sub

【讨论】:

以上是关于我想知道如何运行 vba 脚本来查找和替换仅在一张工作表中而不是整个工作组中的多个单词?的主要内容,如果未能解决你的问题,请参考以下文章

如何仅在一天中的特定时间运行 Python 脚本?

尝试保存时 VBA 宏抛出错误(但仅在一台计算机上)

如何使用 VBA 在 Excel 注释中查找和替换日期格式

如果它们与使用 vba 的条件匹配,则在列中查找最小值和中值

如何为 VBA 查找/替换脚本设置某种数组

如何让 Excel VBA 识别数字单元格?