Excel VBA循环填充某些单元格值
我在VBA做作业。我录制了一个宏,找到了搜索条件为“central”的单元格,然后将其涂成蓝绿色,得到了以下宏:Excel VBA循环填充某些单元格值,excel,vba,loops,Excel,Vba,Loops,我在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, Se
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
单词“central”有23种用法,所以我想我可以在以单元格开头的行上方为k=1到23添加。查找(what…
,然后在上方添加下一个k
,以结尾,但当我尝试时,我得到了错误
下一个没有
布鲁斯·韦恩已经告诉过你为什么会犯这个错误了
但是,如果您希望宏查找并处理当前活动工作表中出现的所有“central”(无论有多少),则可以将find()
方法包装在循环中,直到找到所有需要的出现,如下所示(注释中的解释):
Dim f As范围
将第一个地址设置为字符串
使用ActiveSheet.UsedRange引用当前活动工作表使用范围
设置f=.Find(What:=“central”,LookIn:=xlFormulas_
查看:=xlPart,搜索顺序:=xlByRows,搜索方向:=xlNext_
MatchCase:=False,SearchFormat:=False)'搜索第一次出现“central”的引用范围
如果不是f,则“如果找到…”。。。
firstAddress=f.地址“存储第一个出现的单元格”
做
通过f.Interior的参考,发现单元格“Interior”属性
.Pattern=xlSolid
.PatternColorIndex=xlAutomatic
.Color=6723891
.TintAndShade=0
.PatternTintAndShade=0
以
设置f=.FindNext(f)'搜索下一个“中心”事件
循环,而f.Address firstAddress'循环,直到返回到初始出现
如果结束
以
布鲁斯·韦恩已经告诉过你为什么会出错
但是,如果您希望宏查找并处理当前活动工作表中出现的所有“central”(无论有多少),则可以将find()
方法包装在循环中,直到找到所有需要的出现,如下所示(注释中的解释):
Dim f As范围
将第一个地址设置为字符串
使用ActiveSheet.UsedRange引用当前活动工作表使用范围
设置f=.Find(What:=“central”,LookIn:=xlFormulas_
查看:=xlPart,搜索顺序:=xlByRows,搜索方向:=xlNext_
MatchCase:=False,SearchFormat:=False)'搜索第一次出现“central”的引用范围
如果不是f,则“如果找到…”。。。
firstAddress=f.地址“存储第一个出现的单元格”
做
通过f.Interior的参考,发现单元格“Interior”属性
.Pattern=xlSolid
.PatternColorIndex=xlAutomatic
.Color=6723891
.TintAndShade=0
.PatternTintAndShade=0
以
设置f=.FindNext(f)'搜索下一个“中心”事件
循环,而f.Address firstAddress'循环,直到返回到初始出现
如果结束
以
您是否调暗k
?在关闭以
结束之前,您不能关闭For
循环。你必须在“块”中关闭它们。将下一个k
放在结束于
之后。是否调暗k
?在关闭结束于
之前,不能关闭For
循环。你必须在“块”中关闭它们。将下一个k
放在结尾后
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