在特定行中查找和replace整个工作簿

Dim sht As Worksheet Dim fnd As Variant Dim rplc As Variant fnd = "April" rplc = "May" For Each sht In ActiveWorkbook.Worksheets   sht.Cells.Replace what:=fnd, Replacement:=rplc, _     LookAt:=xlPart, SearchOrder:=xlByRows, MatchCase:=False, _     SearchFormat:=False, ReplaceFormat:=False Next sht End Sub 

我有下面的代码,我需要它来查找和replace整个工作簿,但只在第30行。我将如何编辑代码来做到这一点?

两件事情。

首先,不要使用fnd和rplc的变体; 使用string。

其次,指定要replace的范围,而不是仅使用“单元格”。

 Sub Replacer() Const csFnd As String = "April" Const csRpl As String = "May" Const csRow As String = "A30" Dim sht As Worksheet For Each sht In ActiveWorkbook.Worksheets sht.Range(csRow).EntireRow.Replace _ what:=csFnd, _ Replacement:=csRpl Next sht End Sub 

在代码的顶部使用常量来保存不变的文本,而不是在代码的主体中放置variable = "String"也是一个很好的做法。 顶部的常量保持更容易。