[英]Change row background color depending on cell value vba
如果日期是今天(日期以A7開頭的A列中的日期),我想更改行的背景顏色,但是它不起作用。 歡迎任何幫助。 謝謝。
Sub Update_Row_Colors()
Dim LRow As Integer
Dim LCell As String
Dim LColorCells As String
LRow = 7
While LRow < 50
LCell = "A" & LRow
'Color will changed in columns A to AM
LColorCells = "A" & LRow & ":" & "AM" & LRow
Select Case Left(Range(LCell).Value, 6)
Case Now
Range(LColorCells).Interior.ColorIndex = 34
Range(LColorCells).Interior.Pattern = xlSolid
Case Else
Rows(LRow & ":" & LRow).Select
Range(LColorCells).Interior.ColorIndex = xlNone
End Select
LRow = LRow + 1
Wend
End Sub
我認為問題是您在嘗試將其與日期進行比較的同時使用Now(當前)返回當前日期時間。 嘗試更改:
Case Now
至
Case Date()
您可以使用日期,如@Wouter所述。
您還需要將Left(Range(LCell).Value, 6)
更改為Left(Range(LCell).Value, 10)
如果要使用Now
則還需要使用Left
函數從Now
值中刪除時間。
請參閱下面的工作答案。
還要記住,當您要標注變量的大小以引用Row
或Column
時,請始終使用Long
。
Sub Update_Row_Colors()
'Always want to use a long for referencing a Row or Column
Dim LRow As Long
Dim LCell As String
Dim LColorCells As String
LRow = 7
While LRow < 50
LCell = "A" & LRow
'Color will changed in columns A to AM
LColorCells = "A" & LRow & ":" & "AM" & LRow
Select Case Left(Range(LCell).Value, 10)
Case Left(Now, 10)
Range(LColorCells).Interior.ColorIndex = 34
Range(LColorCells).Interior.Pattern = xlSolid
Case Else
Rows(LRow & ":" & LRow).Select
Range(LColorCells).Interior.ColorIndex = xlNone
End Select
LRow = LRow + 1
Wend
End Sub
只是一條額外的信息,您可以通過更好地使用Range
來縮短/清理代碼,請參見下文。
我已經包含了一行來檢查已使用的行,請注意,即使該Row
有空格“”也將對其進行計數。
Option Explicit
Sub Update_Row_Colors()
Dim LRow As Long
Dim RowRange As Range
Dim LastRow As Long
LastRow = ActiveSheet.Range("A1").SpecialCells(xlCellTypeLastCell).Row
For LRow = 7 To LastRow
Set RowRange = Range(Cells(LRow, "A"), Cells(LRow, "AM"))
If Left(Cells(LRow, "A").Value, 10) = Left(Now, 10) Then
RowRange.Interior.ColorIndex = 34
RowRange.Interior.Pattern = xlSolid
Else
RowRange.Interior.ColorIndex = xlNone
End If
Next LRow
End Sub
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.