1

使用 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

有没有更好的方法来做到这一点?

4

1 回答 1

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运行它以使其在控制台窗口中可见。

于 2012-10-13T23:27:01.140 回答