根据单元格值vba更改行背景颜色
如果date是今天(date在A列以A7开始),但是它不起作用,我想要更改行背景颜色。 欢迎任何帮助。 谢谢。
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,它返回当前的date时间,而你试图将它与date进行比较。 尝试改变:
Case Now
至
Case Date()
你可以使用date作为@Wouter提到。
您还需要将Left(Range(LCell).Value, 6)
更改为Left(Range(LCell).Value, 10)
如果你想使用Now
那么你还需要使用Left
函数来从Now
值中删除时间。
请参阅下面的工作答案。
另外请记住,当您想要定义一个variables来引用一个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
,见下文。
我已经包括了一行来检查使用的行,请注意,即使在行中有一个空格“”是会计算它。
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