将表列与excel VBA中的当前日期进行比较

时间:2016-08-20 03:53:26

标签: excel vba excel-vba

我试图写一个excel VBA来比较一个表的列和当前日期,并突出显示是否为真。

以下是一个示例表:

enter image description here

我正在处理的代码是:

Private Sub Workbook_Open()
    Dim tbl As Excel.ListObject 'Table name
    Dim lr As Excel.ListRow 'Row index
    Dim ws As Excel.Worksheet 'Work sheet
    'column names
    Dim keepInTouch As Range, invite As Range, present As Range, follow As Range

    Set ws = ThisWorkbook.Worksheets(1)                                 'select work book index 1
    Set tbl = ws.ListObjects("ContactList")                             'set ContactList to tbl
    Set keepInTouch = tbl.ListColumns("Keep in Touch").DataBodyRange    'Select the appropreate header
    Set invite = tbl.ListColumns("Invite").DataBodyRange
    Set present = tbl.ListColumns("Present").DataBodyRange
    Set follow = tbl.ListColumns("Follow").DataBodyRange
    'MsgBox tbl
    For Each lr In tbl.ListRows
        If lr.Range(1, tbl.ListColumns("Keep in Touch").Index).Value <> Date Then
            keepInTouch.Interior.ColorIndex = xlNone
            keepInTouch.Font.ColorIndex = 1
            keepInTouch.Font.Bold = False
        'If keepInTouch(1).Value = Date And keepInTouch(1).Value <> "" Then
        ElseIf lr.Range(1, tbl.ListColumns("Keep in Touch").Index).Value = Date Then
            keepInTouch.Interior.ColorIndex = 3
            keepInTouch.Font.ColorIndex = 2
            keepInTouch.Font.Bold = True
        End If
        Next lr
End Sub

第19行:If keepInTouch.Index = Date And keepInTouch.Index <> "" Then导致

Run time error '438':
Object doesn't support this property or method.

这样做的正确方法是什么?

1 个答案:

答案 0 :(得分:0)

    If lr.Range(1, tbl.ListColumns("Keep in Touch").Index).Value = Date Then

例如lr.Range(1, 2)是ListRow范围中的第二个列单元格

keepInTouchIndex = tbl.ListColumns("Keep in Touch").Index
NameIndex = tbl.ListColumns("Name").Index

For Each lr In tbl.ListRows
    With lr.Range.Cells(1, NameIndex)
        If lr.Range.Cells(1, keepInTouchIndex).Value <> Date Then
            .Interior.ColorIndex = 3
            .Font.ColorIndex = 2
            .Font.Bold = True
        Else
            .Interior.ColorIndex = xlNone
            .Font.ColorIndex = 1
            .Font.Bold = False
        End If
    End With
Next lr