我必须在名为“Report”的工作表中对我的数据应用两个条件格式(行数不固定)。我可以通过条件格式化“管理规则”选项来完成这些操作。所以我尝试录制宏,但不幸的是我没有看到任何代码记录。
条件格式1:
=$F5="NH Orientation" , then Color (242,220,219)
条件格式2:
=OR($O4<4,$G4="Elective"), then color (242,220,219)
我将把第2行及以下的彩色单元格剪切并粘贴到另一张名为“已删除”的表格中
我希望在我的Excel中有宏的这些条件。
答案 0 :(得分:1)
您决定如何调整,但以下是主要元素:
Option Explicit
Public Sub AddRules()
Dim wb As Workbook
Dim ws As Worksheet
Set wb = ThisWorkbook
Set ws = ThisWorkbook.Worksheets("Report") ' change
Dim rule1 As FormatCondition
Dim rule2 As FormatCondition
Dim lastRow As Long
lastRow = GetLastRow(ws, 1)
If lastRow < 4 Then
MsgBox "Invalid number of rows"
Exit Sub
End If
With ws.Range("A4:V" & lastRow)
.FormatConditions.Delete
Set rule1 = .FormatConditions.Add(Type:=xlExpression, _
Formula1:="=$F5=""NH Orientation""")
rule1.StopIfTrue = True 'Change as required
Set rule2 = .FormatConditions.Add(Type:=xlExpression, _
Formula1:="=OR($O4<4,$G4=""Elective"")")
Dim i As Long
For i = 1 To 2
With .FormatConditions(i)
With .Interior
.PatternColorIndex = xlAutomatic
.Color = RGB(242, 220, 219)
.TintAndShade = 0
End With
End With
Next i
End With
End Sub
Public Function GetLastRow(ByVal ws As Worksheet, Optional ByVal columnNumber As Long = 1) As Long
With ws
GetLastRow = .Cells(.Rows.Count, columnNumber).End(xlUp).Row
End With
End Function
参考:
答案 1 :(得分:0)
我修改如下,现在正在运行。请告知是否可以改进。
Sub AddRules()
Dim ws As Worksheet
Set ws = Sheets("Report")
Dim lastRow As Long
lastRow = GetLastRow(ws, 1)
If lastRow < 4 Then
MsgBox "Invalid number of rows"
Exit Sub
End If
With ws.Range("A4:V" & lastRow)
.FormatConditions.Delete
Set rule1 = .FormatConditions.Add(Type:=xlExpression, _
Formula1:="=$F4=""NH Orientation""")
With rule1
.Interior.Color = RGB(242, 250, 219)
End With
End With
With ws.Range("A4:V" & lastRow)
Set rule2 = .FormatConditions.Add(Type:=xlExpression,Formula1:="=AND($O4<4,$G4=""Elective"")")
With rule2
.Interior.Color = RGB(242, 210, 219)
End With
End With
End Sub
Function GetLastRow(ByVal ws As Worksheet, Optional ByVal columnNumber As Long = 1) As Long
With ws
GetLastRow = .Cells(.Rows.Count, columnNumber).End(xlUp).Row
End With
End Function