gpt4 book ai didi

events - 我如何知道 VBA 宏中的文件已被修改?

转载 作者:行者123 更新时间:2023-12-02 07:04:50 25 4
gpt4 key购买 nike

有没有办法在 VBA(本质上是 VB6)中监视文件,以便我知道文件何时被修改? -- 类似于 this只是我不想知道文件何时未使用,只是当它修改时。

我找到的答案建议使用“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

关于events - 我如何知道 VBA 宏中的文件已被修改?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1586169/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com