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
我有以下代码,我需要它来查找和替换整个工作簿,但只在第30行。如何编辑代码来执行此操作?
答案 0 :(得分:1)
两件事。
首先,不要为fnd和rplc使用变体;使用字符串。
其次,指定要替换的范围,而不仅仅是使用" Cells"。
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"
放在代码体中也是一种很好的做法。使用顶部的常量更容易维护。