我怎么知道当一个文件已经在VBA宏被修改?(How do I know when a file ha

2019-08-20 03:31发布

有没有一种方法来观看在VBA(基本上是VB6)的文件,所以我知道该文件已被修改? -类似这只是我不想知道,当一个文件是未使用的 ,它的修改只是当。

我发现这些问题的答案都使用“FileSystemWatcher的”和Win32 API“FindFirstChangeNotification”推荐。 我无法弄清楚如何使用,虽然这些,任何想法?

Answer 1:

好吧,我把一个解决方案,它能够检测到文件系统的变化,在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


Answer 2:

你应该考虑使用WMI临时事件消费者看文件,沿线建议这里 ,但缩小它归结为一个特定的文件,而不是一个文件夹

(这是假设你不能只是盯紧该文件的修改日期属性..)



Answer 3:

看看这里 。 该页面有一个“观看指南演示” VB样品,由Bryan斯塔福德。



Answer 4:

我把它变成VB6,运行显示:ERROR看。



文章来源: How do I know when a file has been modified in a VBA Macro?