VBA – 循环遍历一系列工作表中的所有ListObjects

我有一个表格条件格式macros(感谢Jeeped),我想扩展到遍历一系列工作表中的所有表。 我怀疑这不是最有效的方法,但它是最好的,我可以拼凑在一起,即使这样做是行不通的。 到目前为止,我被困在两点以下。 任何援助非常感谢!

1)设置ws等于多个工作表代号(例如Set ws = Worksheets(5,6,7)

2)设置运行时错误的范围Set myRange = ws.ListObjects.DataBodyRange产生“运行时错误'438':对象不支持此属性或方法”

目前的代码是:

 Sub ConditionalFormatting() Dim ws As Excel.Worksheet Dim lo As Excel.ListObject Dim myRange As Range Set ws = Worksheet(5) 'Would like to expand to include multiple worksheets! Set myRange = ws.ListObjects.DataBodyRange For Each lo In ws.ListObjects With lo.FormatConditions .FormatConditions.Delete Call FormatRange(myRange, 10, "$E5=INDEX(Location,1,1)") 'Warehouse1 Call FormatRange(myRange, 10, "$E5=INDEX(Location,2,1)") 'Warehouse2 Call FormatRange(myRange, 10, "$E5=INDEX(Location,3,1)") 'Warehouse3 End With Next lo End Sub Public Sub FormatRange(r As Range, clr As Integer, frml As String) r.FormatConditions.Add Type:=xlExpression, Formula1:=frml r.FormatConditions(r.FormatConditions.Count).Font.colorindex = clr With r.FormatConditions(1).Borders(xlTop) .LineStyle = xlContinuous .Color = color .TintAndShade = 0 .Weight = xlThin End With With r.FormatConditions(1).Borders(xlBottom) .LineStyle = xlContinuous .Color = color .TintAndShade = 0 .Weight = xlThin End With r.FormatConditions(1).StopIfTrue = False End Sub 

未经testing:

 Sub ConditionalFormatting() Dim ws As Excel.Worksheet Dim lo As Excel.ListObject Dim myRange As Range Dim i For Each i in Array(5, 6, 7) Set ws = Worksheets(i) For Each lo In ws.ListObjects Set myRange = lo.DataBodyRange myRange.FormatConditions.Delete FormatRange myRange, 10, "$E5=INDEX(Location,1,1)" 'Warehouse1 FormatRange myRange, 10, "$E5=INDEX(Location,2,1)" 'Warehouse2 FormatRange myRange, 10, "$E5=INDEX(Location,3,1)" 'Warehouse3 Next lo Next i End Sub 

就像循环访问Listobject集合“Listobjects”一样,您可以遍历Worksheet集合“WorkSheets”

 Dim ws As Worksheet For Each ws In ThisWorkbook.Worksheets '... Next ws