繁体   English   中英

如何检查我的工作簿 (excel) 是否从 word 文档中打开?

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM