有没有办法在 VBA(本质上是 VB6)中查看文件,以便我知道文件何时被修改?- 与此类似,只是我不想知道文件何时未使用,只是何时修改。
我找到的答案建议使用“FileSystemWatcher”和 Win32 API“FindFirstChangeNotification”。我不知道如何使用这些,知道吗?
有没有办法在 VBA(本质上是 VB6)中查看文件,以便我知道文件何时被修改?- 与此类似,只是我不想知道文件何时未使用,只是何时修改。
我找到的答案建议使用“FileSystemWatcher”和 Win32 API“FindFirstChangeNotification”。我不知道如何使用这些,知道吗?
好的,我在 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
您应该考虑使用 WMI 临时事件使用者来观看文件,按照此处建议的方式,但将其缩小到特定文件而不是文件夹
(这是假设您不能只关注文件的修改日期属性..)
看看这里。该页面有一个“Watch Directory Demo”VB 示例,作者为 Bryan Stafford。
我把它带入 vb6,run,display:ERROR 观看。