2012-09-21 178 views
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 

有沒有更好的方法來做到這一點?

回答

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命令運行它,使之在控制檯窗口中可見。

相關問題