用于存放新文件的VBA监视器文件夹 [英] VBA monitor folder for new files

查看:12
本文介绍了用于存放新文件的VBA监视器文件夹的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我正在尝试编写一个VBA程序,该程序将监视文件夹中的新文件,然后对它们执行操作。我找到了一些关于使用WMI API的有前景的示例:

Receive notification of file creation in VBA without polling

http://www.mrexcel.com/forum/excel-questions/211547-monitor-new-files-folder.html

https://blogs.technet.microsoft.com/heyscriptingguy/2004/10/11/how-can-i-automatically-run-a-script-any-time-a-file-is-added-to-a-folder/

但事情是这样的:似乎每个人对这些示例采取的策略是将VBA作为宏连接到Excel电子表格中。人们认为Excel是穷人的编程环境。当然可以。问题是,当用户用宏关闭这个神奇的EXCEL文件时,我需要它来运行。

直觉告诉我,我需要用VB6.0或C#在VB6.0或C#中创建一个完整的Windows应用程序,并将该应用程序作为某种计划任务在后台运行。这是正确的途径,还是我在这些Excel/VBA教程中遗漏了一些简单的东西?

(对问题的概括性表示歉意。我知道社区喜欢具体的问题。)

vba

vba和推荐答案很相似。对于WMI来说,情况大同小异。这里有三个剧本。您还可以将WMI与事件处理程序连接在一起,这样您就可以拥有多个事件,而不是这里所示的一个事件。

VB6是可编译为可执行文件的VBA。VB6托管VBA语言,Office也是如此。

InstanceCreationEvent

Set objWMIService = GetObject("winmgmts:{impersonationLevel=impersonate}!\.
ootcimv2")
Set colMonitoredEvents = objWMIService.ExecNotificationQuery _
("SELECT * FROM __InstanceCreationEvent WITHIN 10 WHERE Targetinstance ISA 'CIM_DirectoryContainsFile' and TargetInstance.GroupComponent= 'Win32_Directory.Name=""c:\\scripts""'")
Do
    Set objLatestEvent = colMonitoredEvents.NextEvent
    Wscript.Echo objLatestEvent.TargetInstance.PartComponent
Loop

InstanceModificationEvent

Set objWMIService = GetObject("winmgmts:{impersonationLevel=impersonate}!\.
ootcimv2")
Set colMonitoredEvents = objWMIService.ExecNotificationQuery _
("SELECT * FROM __InstanceModificationEvent WITHIN 10 WHERE Targetinstance ISA 'CIM_DirectoryContainsFile' and TargetInstance.GroupComponent= 'Win32_Directory.Name=""c:\\scripts""'")
Do
    Set objLatestEvent = colMonitoredEvents.NextEvent
    Wscript.Echo objLatestEvent.TargetInstance.PartComponent
Loop

InstanceDeletionEvent

Set objWMIService = GetObject("winmgmts:{impersonationLevel=impersonate}!\.
ootcimv2")
Set colMonitoredEvents = objWMIService.ExecNotificationQuery _
("SELECT * FROM __InstanceDeletionEvent WITHIN 10 WHERE Targetinstance ISA 'CIM_DirectoryContainsFile' and TargetInstance.GroupComponent= 'Win32_Directory.Name=""c:\\scripts""'")
Do
    Set objLatestEvent = colMonitoredEvents.NextEvent
    Wscript.Echo objLatestEvent.TargetInstance.PartComponent
Loop

这篇关于用于存放新文件的VBA监视器文件夹的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆