[英]How to check if my Workbook (excel) is open from a word document?
正是我想檢查我的 Excel 工作簿(只有一個)是否打開。 如果它是打開的,那么使用一些代碼從中獲取一些數據否則首先打開我的 Excel 文件並從中獲取一些數據。 只要我正在處理我的 word 文檔,我就想保持我的 Excel 文件始終打開。
這是一個word文檔中的一些代碼來嘗試實現這一點:
Dim appExcel As Excel.Application
Dim xlWBook As Excel.Workbook
On Error Resume Next
Set appExcel = GetObject(, "Excel.Application")
If appExcel Is Nothing Then
Set appExcel = CreateObject("Excel.Application")
Set xlWBook = appExcel.Workbooks.Open(ActiveDocument.Path & strFile)
EndIf
' Some code
xlWBook.Sheets(3).Cells(4,2).value = strData1
' or the other way
strData2 = xlWBook.Sheet(4).Cells(3,5).Value
' ...etc...
xlWBook.Close SaveChanges:=True
appExcel.Quit
Set xlWBook = Nothing
Set appExcel = Nothing
我是否需要關閉它(如上所述),知道我會將這種代碼用於另一個模塊或用戶表單? 我在正確的軌道上嗎? 還是每次打開它然后在完成后關閉它是更好的做法?
我的目標是避免在每次需要時打開和關閉 Excel 文件。 請注意,我首先通過單擊功能區中的按鈕直接在其上輸入數據來打開我的 Excel 文件,因此用戶可能會保持打開狀態,但他可能會關閉它。
最后一個想法:我是否應該確定 excel 文件是否打開? 如果是,請關閉它,然后在每次需要時打開並關閉它。
謝謝。
請嘗試這種方式:
Sub CheckOpenWbinEccel()
Dim appExcel As Excel.Application, boolFound as Boolean
Dim xlWBook As Excel.Workbook, wb As Excel.Workbook
On Error Resume Next
Set appExcel = GetObject(, "Excel.Application")
If appExcel Is Nothing Then
Err.Clear: On Error GoTo 0 'it is good to clear the error and make VBA raise other errors, if the case
Set appExcel = CreateObject("Excel.Application")
Set xlWBook = appExcel.Workbooks.Open(ActiveDocument.path & strFile)
Else
On Error GoTo 0' make VBA raise other errors, if the case
For Each wb In appExcel
If wb.FullName = ActiveDocument.path & strFile Then
Set xlWBook = wb: boolFound = True: Exit For' no need to close and reopen it
End If
If Not boolFound Then Set xlWBook = appExcel.Workbooks.Open(ActiveDocument.path & strFile)
Next
End If
' Some code
xlWBook.Sheets(3).Cells(4, 2).value = strData1
' or the other way
strData2 = xlWBook.Sheet(4).Cells(3, 5).value
' ...etc...
'if you want keeping Excel session and workbook open, comment the next two lines:
xlWBook.Close SaveChanges:=True 'here
appExcel.Quit 'and here
Set xlWBook = Nothing
Set appExcel = Nothing
End Sub
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.