excel VBA如何在用户打开文件时自动运行代码

时间:2017-10-06 08:36:44

标签: excel vba excel-vba

我有这个代码检查日期并根据日期填充单元格。

我需要的是当用户打开文件并写日期时,系统会直接检查日期并填写正确的颜色。

发生的事情是,在用户编写日期后,他需要点击宏图标才能使代码采取行动。

的代码:

Sub test()
Dim i As Integer
Dim OfficerList(4) As String


For i = Range("C5000").End(xlUp).Row To 2 Step -1 'Range upto 5000, chnge this as per your requirment'

    Select Case VBA.CDate(Cells(i, 3))

    Case Is < VBA.Date()
        Cells(i, 3).Interior.Color = vbGreen

    Case Is = VBA.Date()
        Cells(i, 3).Interior.Color = vbYellow

    Case Is > VBA.Date()
        Cells(i, 3).Interior.Color = vbRed

   End Select
Next
End Sub
谁能帮助我吗? 还是有更好的主意?

1 个答案:

答案 0 :(得分:0)

此代码应该完成工作。

'This function is called everytime a cell is edited in the worksheet
'NOTE: This macro should be placed in the same worksheet object of your VBA Project
'that has the same worksheet name as the worksheet with all the dates
Private Sub Worksheet_Change(ByVal Target As Range)

    Dim DateCells As Range
    Set DateCells = Range("C2:C5000")

    'If the user changed one of the date cell run the macro, else do nothing
     If (Not Application.Intersect(DateCells, Range(Target.Address)) Is Nothing) Then
        test   'Call your macro here
    End If

End Sub

'This function is called everytime the workbook is opened
'NOTE: This macro should be placed in the 'ThisWorkbook' object of your VBA 
Project
Private Sub Workbook_Open()
    test    'Call your macro here
End Sub