有沒有辦法在VBA中觀察文件(實際上是VB6),以便知道文件何時被修改? - 類似this只我不想知道什麼時候一個文件是未使用,就是當它的修改爲。如何知道VBA宏中的文件何時被修改?
我發現的答案建議使用「FileSystemWatcher」和Win32 API「FindFirstChangeNotification」。我不知道如何使用這些,但任何想法?
有沒有辦法在VBA中觀察文件(實際上是VB6),以便知道文件何時被修改? - 類似this只我不想知道什麼時候一個文件是未使用,就是當它的修改爲。如何知道VBA宏中的文件何時被修改?
我發現的答案建議使用「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臨時事件消費者看文件,沿線建議here但縮小它歸結爲一個特定的文件夾
,而不是(這是假設你不能只是保持一個注意文件的修改日期屬性..)
看一看here。該頁面由Bryan Stafford提供「Watch Directory Demo」VB示例。
我把它放到vb6中,運行,顯示:ERROR在看。
你有C盤下的「scripts」目錄嗎? – 2010-02-11 00:08:54