我有一个表条件格式化宏(感谢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
答案 0 :(得分:2)
未测试:
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
答案 1 :(得分:0)
就像你循环遍历listobject集合" Listobjects",你可以遍历工作表集合" WorkSheets"
Dim ws As Worksheet
For Each ws In ThisWorkbook.Worksheets
'...
Next ws
答案 2 :(得分:0)
将此示例用于我的代码以重置我所有表的过滤器
Dim ws As Worksheet
Dim lo As ListObject
For Each ws In ThisWorkbook.Worksheets
For Each lo In ws.ListObjects
If lo.ShowAutoFilter Then
If lo.AutoFilter.FilterMode Then
lo.AutoFilter.ShowAllData
End If
End If
Next lo
Next ws