簡體   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