VBA(基本的にVB6)でファイルを監視して、ファイルがいつ変更されたかを知る方法はありますか?--これと同様に、ファイルがいつ使用されていないのか、いつ変更されているのかを知りたくありません。
私が見つけた答えは、「FileSystemWatcher」とWin32API「FindFirstChangeNotification」の使用を推奨しています。これらの使い方がわかりませんが、何か考えはありますか?
VBA(基本的にVB6)でファイルを監視して、ファイルがいつ変更されたかを知る方法はありますか?--これと同様に、ファイルがいつ使用されていないのか、いつ変更されているのかを知りたくありません。
私が見つけた答えは、「FileSystemWatcher」とWin32API「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 一時イベント コンシューマーを使用してファイルを監視することを検討する必要があります。ここで提案されている行に沿って、フォルダーではなく特定のファイルに絞り込む必要があります。
(これは、ファイルの Modified Date プロパティを監視することはできないと想定しています..)
こちらをご覧ください。このページには、Bryan Stafford による「Watch Directory Demo」VB サンプルがあります。
vb6,run,display:ERROR ウォッチングに取り入れます。