2013-07-09 95 views
0

編輯:在將特定的Excel文件或其窗口放到前面之前,我需要檢查它是否正在運行/仍然打開。檢查一個特定的Excel文件在打開多個Excel文件時是否打開並激活它

舊問題: 我想設置一個特定的Excel窗口到前面。

有了這個VBScript代碼,我可以通過它的名字激活一個單獨的Excel窗口。但是由於打開了多個Excel窗口,它不再工作。在這種情況下,它不會找到所需的窗口,並且無法檢查它是否打開。所以它總是會說ExcelFileName沒有打開。

Set WshShell = WScript.CreateObject ("WScript.Shell") 
if WshShell.AppActivate(ExcelFileName) = True then 
    wscript.echo ExcelFileName & " is opened." 
    WshShell.sendkeys "%x" 'in Excel 2003 this would had opened the extra-menu-droplist of the menu-bar. Now it just activates Excel. 
else 
    wscript.echo ExcelFileName & " is not open." 
End if 

如何使它可以與多個打開的Excel窗口一起使用?

+0

一個簡單的'CreateObject(「WScript.Shell」).AppActivate「Microsoft Excel」'不起作用? –

+0

是的,我很驚訝它工作正常。但是我很抱歉,我注意到我把這個問題寫錯了,我的錯!除了激活一個窗口,我想在之前檢查它是否可用或正在運行。我想在激活它之前檢查是否打開了特定的Excel文件。我現在編輯我的問題。 – Eleandro

+0

看看這裏:[檢查工作簿是否在任何Excel實例中打開](http://www.thecodenet.com/articles.php?id=1)。不幸的是,它不能以與VBScript相同的方式工作,但它解釋了這個問題。 – Eleandro

回答

5

因此,您想要檢測是否打開了具有給定名稱的工作簿?可以這樣做在VBScript:

ExcelFileName = "some.xlsx" 

On Error Resume Next 
Set xl = GetObject(, "Excel.Application") 'attach to running Excel instance 
If Err Then 
    If Err.Number = 429 Then 
    WScript.Echo "Workbook not open (Excel is not running)." 
    Else 
    WScript.Echo Err.Description & " (0x" & Hex(Err.Number) & ")" 
    End If 
    WScript.Quit 1 
End If 
On Error Goto 0 

Set wb = Nothing 
For Each obj In xl.Workbooks 
    If obj.Name = ExcelFileName Then 'use obj.FullName for full path 
    Set wb = obj 
    Exit For 
    End If 
Next 
If wb Is Nothing Then 
    WScript.Echo "Workbook not open." 
    WScript.Quit 1 
End If 

GetObject只能連接到最先推出的Excel實例,雖然。您需要終止該實例才能連接到下一個實例(請參閱here)。但是,由於這是在已經運行的實例中打開工作簿的默認設置,因此上面應該適用於大多數場景。

+0

非常感謝!我在'如果wb = Nothing Then'這行中發現一個錯誤,這應該是'If wb is Nothing Then',然後它工作正常。請編輯您的帖子,我已經打算將其標記爲答案。 – Eleandro

+1

謝謝你的擡頭。固定。 –