2016-08-20 141 views
-1

我想寫一個excel VBA來比較一個表與當前日期的列,並突出顯示如果是true。在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. 

是什麼這樣做的正確方法?

+0

第二列單元應當與[條件格式](https://www.ablebits.com/office-addins-blog/容易2014/06/17/Excel的條件格式日期/#基於當前日期)和範圍沒有'.Index' ..也許你的意思是'.Value' – Slai

+0

@Slai我已經嘗試'.Value'但它給了'運行時錯誤'13':類型不匹配' – Amir

+0

使用'如果keepInTouch(1).Value = Date Then'因爲您已經檢查是否是這個字符串,所以不需要檢查一個零長度的字符串當前日期。 – Jeeped

回答

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 
+0

它給出相同的錯誤消息。 '438' :( – Amir

+0

@Amir我改變了一下後 – Slai

+0

我已經採取了變化,在每個循環之後,每個單元格的格式將被默認爲 *主代碼更新了更改 – Amir

相關問題