我在VBA做作业。我录制了一个宏,它找到了具有搜索条件' central'的单元格,然后我将它涂成了蓝绿色并得到了以下宏:
Sub Color()
' Color Macro
' Color a region
'
' Keyboard Shortcut: Ctrl+m
'
Cells.Find(What:="central", After:=ActiveCell, LookIn:=xlFormulas, _
LookAt:=xlPart, SearchOrder:=xlByRows, SearchDirection:=xlNext, _
MatchCase:=False, SearchFormat:=False).Activate
With Selection.Interior
.Pattern = xlSolid
.PatternColorIndex = xlAutomatic
.Color = 6723891
.TintAndShade = 0
.PatternTintAndShade = 0
End With
End sub
“中心”这个词有23个出现。所以我想我可以在以for k=1 to 23
开头的行上方添加cells.find(what...)
,然后在Next K
上方添加end with
但是当我尝试时我会收到错误
其次没有
答案 0 :(得分:2)
布鲁斯·韦恩已经告诉过你为什么会遇到这个错误
但是如果你希望你的宏在你当前活动的工作表中找到并处理所有出现的“central”,无论它们有多少,那么你可以将Find()
方法包装在一个循环中,直到所有想要的发现的事件如下(评论中的解释):
Dim f As Range
Dim firstAddress As String
With ActiveSheet.UsedRange 'reference currently active sheet used range
Set f = .Find(What:="central", LookIn:=xlFormulas, _
LookAt:=xlPart, SearchOrder:=xlByRows, SearchDirection:=xlNext, _
MatchCase:=False, SearchFormat:=False) 'search referenced range for first occurrence of "central"
If Not f Is Nothing Then ' if found...
firstAddress = f.Address ' store first occurrence cell
Do
With f.Interior 'reference found cell "Interior" property
.Pattern = xlSolid
.PatternColorIndex = xlAutomatic
.Color = 6723891
.TintAndShade = 0
.PatternTintAndShade = 0
End With
Set f = .FindNext(f) ' search for the next "central" occurrence
Loop While f.Address <> firstAddress ' loop till you wrap back to initial occurrence
End If
End With