繁体   English   中英

根据单元格的输入值对行进行颜色格式化

[英]Color formatting of Rows based on input values for a cell

工作表中有一些数据,其中包括时间列。 提供时间范围作为输入,以格式化该时间范围内时间单元的颜色。 还希望对包含那些单元格的行进行颜色格式化,但在输出中无法观察到。 要提及的是,有时作为输入提供的开始时间或结束时间与任何时间单元的值都不匹配。

附带的是代码,没有提供所需的输出。

任何帮助将不胜感激。

    Dim ws As Worksheet
    Dim timeRange As Range

 Set ws = Sheets("Worksheet") 'Name of my worksheet goes here. 
 Set timeRange = ws.Range("D:D")

'input the lower limit and the upper limit of the search range
Dim Start_Time As Variant
Dim End_Time As Variant

Start_Time = InputBox(prompt:="Enter the Start_Time(hh:mm:ss.000)")
End_Time = InputBox(prompt:="Enter the End_Time(hh:mm:ss.000)")


    timeRange.FormatConditions.Add Type:=xlCellValue, Operator:=xlBetween, _
    Formula1:=Start_Time, Formula2:=End_Time

    timeRange.FormatConditions(timeRange.FormatConditions.Count).SetFirstPriority

 With timeRange.FormatConditions(1).Font
    .Color = -16383844
    .TintAndShade = 0
End With
With timeRange.FormatConditions(1).Interior
    .PatternColorIndex = xlAutomatic
    .Color = 13551615
    .TintAndShade = 0
End With
timeRange.FormatConditions(1).StopIfTrue = False


 'Loop to format the rows that contains those time values
 Dim Range_Search As String
For Each c In Range("D:D")
If c.Interior.Color = 13551615 Then
    Range_Search = "A" & c.Row & ":" & "H" & c.Row
    ws.Range(Range_Search).Interior.Color = 13551615
End If
Next c

您代码中的最终循环将无法正常工作。 您需要将其更改为:

For Each c In Range("D:D")
    If c.Interior.Color = 13551615 Then
        Range_Search = "A" & c.Row & ":" & "H" & c.Row
        Range(Range_Search).Select
        Selection.Interior.Color = 13551615
    End If
Next c

我不确定您的陈述中的“ Let”应该做什么,但这不是必需的。 另外,您需要从单元格c中获取行,而不仅仅是c。

为了使它更好,我将参考工作表中的单元格,因为这将防止选择不同的工作表时可能出现的问题:

Dim ws As worksheet
Dim timeRange As Range

Set ws = Sheets("mySheet") 'Obviously change this to your sheet name
Set timeRange = ws.Range("D:D")

然后替换“选择”。 与“ timeRange”。 在您的代码中,所以

Selection.FormatConditions.Add Type:=xlCellValue, Operator:=xlBetween, _
Formula1:=Start_Time, Formula2:=End_Time

变成:

timeRange.FormatConditions.Add Type:=xlCellValue, Operator:=xlBetween, _
Formula1:=Start_Time, Formula2:=End_Time

然后更改您的最终循环以执行类似的操作:

For Each c In timeRange
    If c.Interior.Color = 13551615 Then
        ws.Range("A" & c.Row & ":" & "H" & c.Row).Interior.Color = 13551615            
    End If
Next c

选择单元格效率不高,如果在尝试运行代码时无意中选择了其他选项,可能会导致问题。

我想到了。 感谢OpiesDad的帮助。

基本上,vba不能识别格式条件颜色,除非您添加DisplayFormat。 在interior.color命令之前。 像这样。

For Each c In timeRange
If c.**DisplayFormat**.Interior.Color = 13551615 Then
    ws.Range("A" & c.Row & ":" & "H" & c.Row).Interior.Color = 13551615            
End If
Next c

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM