有没有办法在VBA(基本上是VB6)中查看文件,以便我知道文件何时被修改? - 与this类似,只是我不想知道文件何时未使用,就在其修改时。
我发现的答案建议使用“FileSystemWatcher”和Win32 API“FindFirstChangeNotification”。我无法弄清楚如何使用这些,任何想法?
答案 0 :(得分:3)
好的,我在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
答案 1 :(得分:1)
您应该考虑使用WMI临时事件使用者按照建议行here来查看文件,但将其缩小到特定文件而不是文件夹
(这假设您不能只关注文件的修改日期属性..)
答案 2 :(得分:1)
看看here。该页面有一个由Bryan Stafford撰写的“Watch Directory Demo”VB样本。
答案 3 :(得分:0)
我把它带入vb6,运行,显示:ERROR观看。