代码之家  ›  专栏  ›  技术社区  ›  Robin Rodricks

如何知道在VBA宏中何时修改了文件?

  •  2
  • Robin Rodricks  · 技术社区  · 15 年前

    有没有一种方法可以监视vba中的文件(本质上是vb6),以便我知道文件何时被修改?——类似于 this 只是我不想知道什么时候文件 未使用 就在它的时候 被改进的 .

    我找到的答案建议使用“filesystemwatcher”和win32 api“findfirstchangenotification”。我不知道怎么用这些,知道吗?

    4 回复  |  直到 15 年前
        1
  •  2
  •   Robin Rodricks    15 年前

    好的,我在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
    

    复制并粘贴上面附近的子,如果需要初始化全局变量,将自动调用它。

    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
    
        2
  •  1
  •   stuartd saeed    15 年前

    您应该考虑使用wmi临时事件使用者按照建议的行来查看文件。 here 但是缩小到一个特定的文件而不是文件夹

    (假设您不能只关注文件的Modified Date属性..

        3
  •  1
  •   Wim Coenen    15 年前

    看一看 here . 页面有一个“观看目录演示”的vb示例,由布莱恩·斯塔福德提供。

        4
  •  0
  •   hack0573    15 年前

    我把它带进vb6,运行,显示:错误监视。