当单元格值条件失败VBA时更改字体颜色

时间:2018-11-01 18:11:22

标签: excel vba excel-vba

我创建了一个宏来更新某些值,输入这些值后,它们将用于创建文本文件以导入到我们的系统中。

以下是数据输入屏幕的屏幕截图:

enter image description here 下面是我写在工作表上的代码:

Option Explicit
Public Rec_Cnt As Integer
Private Sub Worksheet_Change(ByVal Target As Range)

Dim Rng1 As Range
Dim Rng2 As Range
Dim Rng3 As Range
Dim Rng4 As Range

Rec_Cnt = Sheets("MD").Cells(3, 7)

Set Rng1 = Range("G2:G" & Rec_Cnt + 1)
Set Rng2 = Range("M2:M" & Rec_Cnt + 1)
Set Rng3 = Range("S2:S" & Rec_Cnt + 1)
Set Rng4 = Range("D2:E" & Rec_Cnt + 1)

If Not Application.Intersect(Target, Rng1) Is Nothing Then
    If Len(Target) > 10 Then
       Call Original_Ticket_Greater_Error
    ElseIf Len(Target) < 10 Then
       Call Original_Ticket_Lesser_Error
    ElseIf Len(Target) = 10 Then
        Cells(Target.Row, 8).Value = 9
        Cells(Target.Row, 9).Value = "|"
        Cells(Target.Row, 10).Value = "|"
        Cells(Target.Row, 11).Value = "|"
        Cells(Target.Row, 12).Value = "|"
    Exit Sub
    End If
ElseIf Not Application.Intersect(Target, Rng2) Is Nothing Then
    If Len(Target) > 10 Then
       Call Original_Cnj_Ticket_Greater_Error
    ElseIf Len(Target) < 10 Then
       Call Original_Cnj_Ticket_Lesser_Error
    ElseIf Len(Target) = 10 Then
        Cells(Target.Row, 14).Value = 9
        Cells(Target.Row, 15).Value = "|"
        Cells(Target.Row, 16).Value = "|"
        Cells(Target.Row, 17).Value = "|"
        Cells(Target.Row, 18).Value = "|"
    Exit Sub
    End If
ElseIf Not Application.Intersect(Target, Rng3) Is Nothing Then
    If Len(Target) > 10 Then
       Call Original_Ticket_Greater_Error
    Exit Sub
    ElseIf Len(Target) < 10 Then
       Call Original_Ticket_Lesser_Error
    Exit Sub
    End If
ElseIf Not Application.Intersect(Target, Rng4) Is Nothing Then
    If Cells(Target.Row, 3).Value = "Sales" Or Cells(Target.Row, 3).Value = "Sales Conjunction" Then
        Cells(Target.Row, 6).Value = Application.Sum((Cells(Target.Row, 4).Value), (Cells(Target.Row, 5).Value))
        Cells(Target.Row, 6).Value = Int(Cells(Target.Row, 6).Value * 100)
    End If
End If

End Sub

Sub Original_Ticket_Greater_Error()
    MsgBox "Original Ticket Number is more than 10 characters"
End Sub

Sub Original_Cnj_Ticket_Greater_Error()
    MsgBox "Original Conj. Ticket Number is more than 10 characters"
End Sub

Sub Original_Ticket_Lesser_Error()
    MsgBox "Original Ticket Number is less than 10 characters"
End Sub

Sub Original_Cnj_Ticket_Lesser_Error()
    MsgBox "Original Conj. Ticket Number is less than 10 characters"
End Sub

基于代码,您可以注意到我仅在Target = 10时更新某些单元格,否则不更新。

当目标> 10或<10时,我想将字体更改为RED,并尝试了几个选项,但是字体颜色没有变化。 我用过Target.Font.Color和类似的选项。

非常感谢您的帮助。

谢谢, 萨钦(Sachin)

1 个答案:

答案 0 :(得分:1)

您可以通过一些条件格式来实现。

主页功能区中,单击“条件格式” “管理规则” 。然后选择新规则

home ribbon

在公式文本框中,输入=INDIRECT("G"&ROW())<>10

edit formatting rule

在“应用于”文本框中,输入减去标题=$G$2:$G$1048576的列

conditional formatting rules manager

示例结果:

screenshot