暂停执行直到保存文件

时间:2012-09-21 21:50:23

标签: vbscript

使用vbscript我希望能够创建一个excel对象,允许用户打开文件然后保存后,能够验证文件中的数据。我已经尝试使用WaitForChangedResult来查看文件所在的目录并等待它继续进行更改,但是只有在文件关闭而不保存时才会继续,而不是在保存时。这是代码的样子:

Dim xl As Object
xl = CreateObject("excel.application")
xl.FileDialog(1).AllowMultiSelect = False
xl.FileDialog(1).Title = "Navigate to 60-40 loan calculator"
Dim strFilePathAndName As String
If xl.FileDialog(1).Show() = -1 Then
    strFilePathAndName = xl.FileDialog(3).SelectedItems(1)
Else
    Exit Sub
End If
xl.Visible = True
xl.Workbooks.Open(strFilePathAndName)
Dim strXLTab As String
strXLTab = xl.ActiveSheet.Name


Dim result As System.IO.WaitForChangedResult
Dim directory As String
directory = Environment.GetFolderPath(Environment.SpecialFolder.Desktop)
Dim watcher As New System.IO.FileSystemWatcher(directory, "Calculator.xls")
result = watcher.WaitForChanged(System.IO.WatcherChangeTypes.Changed)
TextBox1.Text = directory

有更好的方法吗?

1 个答案:

答案 0 :(得分:0)

您可以使用以下代码监视文件以进行更改。

只需将代码替换为Wscript.echo命令,即可在更改/创建/删除文件时执行所需的操作。

' Monitors a file for modifications.
Dim intTimer:        intTimer = "2"
Dim strDrive:        strDrive = "c:"
Dim strPath:         strPath = "\\temp\\"
Dim strFile:         strFile = "log.txt"
Dim strComputer:     strComputer = "."
Dim objWMIService:   Set objWMIService = GetObject( "winmgmts:" &  "{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2" )
Dim strQuery:        strQuery = "Select * From __InstanceOperationEvent" & " Within " & intTimer & " Where Targetinstance Isa 'CIM_DataFile'" & " And TargetInstance.Drive='" & strDrive & "'" & " And TargetInstance.Path='" & strPath & "'"
Dim colEvents:       Set colEvents = objWMIService. ExecNotificationQuery (strQuery)
WScript.Echo "Monitoring file changes... Press [Ctrl]-[C] to exit"
Do
    Set objEvent = colEvents.NextEvent()
    Set objTargetInst = objEvent.TargetInstance
    if right(objTargetInst.Name,len(strFile)) = strFile then
        Select Case objEvent.Path_.Class
            Case "__InstanceCreationEvent"
                WScript.Echo "Created: " & objTargetInst.Name
            Case "__InstanceDeletionEvent"
                WScript.Echo "Deleted: " & objTargetInst.Name
            Case "__InstanceModificationEvent"
                WScript.Echo "Modified: " & objTargetInst.Name
        End Select
    end if
Loop

使用 Wscript 运行此功能并且无法显示或使用 Cscript 运行它以使其在控制台窗口中可见。