检查工作表 B 的单元格值并将格式应用于循环中工作表 A 中的范围

问题描述 投票:0回答:1

在使用条件格式创建循环时陷入 Excel VBA 困境。 我必须搜索工作表 B 单元格 G2 的值,并将条件格式应用于工作表 A 从 A2 到 D2 的范围。 发布后,它将检查工作表 B 单元格 A3,并再次根据该值将条件格式应用于工作表 A 范围从 A3 到 D3。 我正在使用脚本,但无法继续进行,因为与循环两个地方感到困惑

Sub formatting()

  Dim rng As Range
  Dim condition1 As FormatCondition, condition2 As FormatCondition

  Set rng = Range("A2", "D2")

   rng.FormatConditions.Delete
   
   Sheets("B").Select

    Range("G2").Select

   Set condition1 = rng.FormatConditions.Add(xlCellValue, xlEqual, "=False")
   Set condition2 = rng.FormatConditions.Add(xlCellValue, xlEqual, "=0")

    With condition1
    With Selection.Font
        .Color = -16776961
        .TintAndShade = 0
    End With
    End With


     With condition2
     With Selection.Font
        .ColorIndex = xlAutomatic
        .TintAndShade = 0
    End With
    End With

End Sub 

无法在工作表 B 中的单元格值之间循环并将此条件应用于工作表 A 中的范围 A:D

excel vba loops if-statement
1个回答
0
投票

要循环遍历工作表 B 中的单元格并将条件格式应用于工作表 A 中的相应范围,您需要将循环合并到 VBA 代码中。

Sub ApplyConditionalFormatting()
    Dim wsA As Worksheet, wsB As Worksheet
    Dim lastRow As Long
    Dim i As Long
    Dim rng As Range
    Dim cellValue As Variant
    
    Set wsA = Sheets("A")
    Set wsB = Sheets("B")
    
    lastRow = wsB.Cells(wsB.Rows.Count, "G").End(xlUp).Row
    
    For i = 2 To lastRow
        cellValue = wsB.Cells(i, "G").Value
        
        Set rng = wsA.Range(wsA.Cells(i, "A"), wsA.Cells(i, "D"))
        
        rng.FormatConditions.Delete
        
        If cellValue = False Or cellValue = 0 Then
            With rng.FormatConditions.Add(Type:=xlExpression, Formula1:="=1=1")
                .Font.Color = RGB(0, 0, 255) 
            End With
        Else
            With rng.FormatConditions.Add(Type:=xlExpression, Formula1:="=1=1")
                .Font.ColorIndex = xlAutomatic
            End With
        End If
    Next i
End Sub
© www.soinside.com 2019 - 2024. All rights reserved.