【发布时间】:2009-10-18 22:13:20
【问题描述】:
有没有办法在 VBA(本质上是 VB6)中查看文件,以便我知道文件何时被修改? -- 类似于this,只是我不想知道文件何时未使用,只是修改。
我找到的答案建议使用“FileSystemWatcher”和 Win32 API“FindFirstChangeNotification”。我不知道如何使用这些,有什么想法吗?
【问题讨论】:
标签: events vba ms-office filesystemwatcher
有没有办法在 VBA(本质上是 VB6)中查看文件,以便我知道文件何时被修改? -- 类似于this,只是我不想知道文件何时未使用,只是修改。
我找到的答案建议使用“FileSystemWatcher”和 Win32 API“FindFirstChangeNotification”。我不知道如何使用这些,有什么想法吗?
【问题讨论】:
标签: events vba ms-office filesystemwatcher
好的,我在 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复制粘贴到上面,如果需要初始化全局变量会自动调用。
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 临时事件使用者来观看文件,按照建议的 here 行,但将其缩小到特定文件而不是文件夹
(这是假设您不能只关注文件的修改日期属性..)
【讨论】:
看看here。该页面有一个“Watch Directory Demo”VB 示例,作者为 Bryan Stafford。
【讨论】:
我把它带入 vb6,运行,显示:错误观看。
【讨论】: