How do I know when a file has been modified in a VBA Macro?

爷,独闯天下 提交于 2019-11-28 12:46:15

Okay, I put together a solution that is able to detect file system changes, in VBA (VB6).

Public objWMIService, colMonitoredEvents, objEventObject

'call this every 1 second to check for changes'
Sub WatchCheck()
On Error GoTo timeout
    If objWMIService Is Nothing Then InitWatch 'one time init'
    Do While True
        Set objEventObject = colMonitoredEvents.NextEvent(1) 
         '1 msec timeout if no events'
        MsgBox "got event"

        Select Case objEventObject.Path_.Class
            Case "__InstanceCreationEvent"
                MsgBox "A new file was just created: " & _
                    objEventObject.TargetInstance.PartComponent
            Case "__InstanceDeletionEvent"
                MsgBox "A file was just deleted: " & _
                    objEventObject.TargetInstance.PartComponent
            Case "__InstanceModificationEvent"
                MsgBox "A file was just modified: " & _
                    objEventObject.TargetInstance.PartComponent
        End Select
    Loop
Exit Sub
timeout:
    If Trim(Err.Source) = "SWbemEventSource" And Trim(Err.Description) = "Timed out" Then
        MsgBox "no events in the last 1 sec"
    Else
        MsgBox "ERROR watching"
    End If
End Sub

Copy and paste this sub near the above, it is called automatically if needed to initialize the global vars.

Sub InitWatch()
On Error GoTo initerr
    Dim watchSecs As Integer, watchPath As String
    watchSecs = 1 'look so many secs behind'
    watchPath = "c:\\\\scripts" 'look for changes in this dir'

    strComputer = "."
    Set objWMIService = GetObject("winmgmts:\\" & strComputer & "\root\cimv2")
    Set colMonitoredEvents = objWMIService.ExecNotificationQuery _
        ("SELECT * FROM __InstanceOperationEvent WITHIN " & watchSecs & " WHERE " _
            & "Targetinstance ISA 'CIM_DirectoryContainsFile' and " _
                & "TargetInstance.GroupComponent= " _
                    & "'Win32_Directory.Name=""c:\\\\scripts""'")

    MsgBox "init done"
Exit Sub
initerr:
    MsgBox "ERROR during init - " & Err.Source & " -- " & Err.Description
End Sub

You should consider using a WMI temporary event consumer to watch the file, along the lines suggested here but narrowing it down to a specific file instead of a folder

(This is assuming you can't just keep an eye on the file's Modified Date property..)

Have a look here. The page has a "Watch Directory Demo" VB sample, by Bryan Stafford.

I take it into vb6,run,display:ERROR watching.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!