0

I'm new to macros and I'm trying to learn how to write some simple expressions. I'd like to compare all the values in a single column to see if they match the current day of the month.

For example: Column H contains a number that corresponds to a random day of the month. I'd like to know how to write an expression in the macro so that if today == the value in column H (in other words, if today is the 19th and the value in column H is 19) then change the cell text color to red (or some other action).

So far I only know how to select a range of cells using: Range("B2, C7, I8") but I don't know how to select an entire column. Can anyone tell me how I could write such an expression?

*Note: I'm not talking about comparing columns across sheets. I just need to compare the values in one column to the current date. Thanks!

4

1 回答 1

1

To act on an entire column, either of these lines will work:

Range("A:A")
Columns("A")

As for checking if a column contains a specific criteria, I would recommend using the worksheet formula Countif:

MsgBox WorksheetFunction.Countif(Columns("A"), Day(Now)) > 0

To find all cells within a column that contain the criteria, you can use the Range.Find method:

Dim rngFound As Range
Dim strFirst As String
Dim lDayNum As Long

lDayNum = Day(Now)
Columns("A").Interior.Color = xlNone

Set rngFound = Columns("A").Find(lDayNum, Cells(Rows.Count, "A"), xlValues, xlWhole)
If Not rngFound Is Nothing Then
    strFirst = rngFound.Address
    Do
        rngFound.Interior.Color = RGB(255, 0, 0)
        Set rngFound = Columns("A").Find(lDayNum, rngFound, xlValues, xlWhole)
    Loop While rngFound.Address <> strFirst
End If

Lastly, this could be more easily accomplished with some conditional formatting.

于 2013-08-19T21:10:16.453 回答