简体   繁体   English

如何参考 OLE 工作簿?

[英]How to refer to OLE Workbook?

In one of my worksheets I have another workbook inserted as an embedded object, which I need to open to read some of its fields.在我的一个工作表中,我插入了另一个工作簿作为嵌入对象,我需要打开它才能阅读其中的一些字段。

I open this file using OLEobj.Verb xlVerbOpen , and assign it to a Workbook variable called wbR .我使用OLEobj.Verb xlVerbOpen打开此文件,并将其分配给名为wbRWorkbook变量。 Because its name may change each time it is opened, the only way I have figured to do so is using ActiveWorkbook .因为每次打开它的名字都可能会改变,所以我想这样做的唯一方法是使用ActiveWorkbook

This works when I run the code line by line.当我逐行运行代码时,这有效。 However when the whole macro is run from a button, most of the time ActiveWorkbook will be considered the same as ThisWorkBook .但是,当从按钮运行整个宏时,大多数情况下ActiveWorkbook将被视为与ThisWorkBook相同。 I tried using Wait and Sleep.我尝试使用等待和睡眠。

The part giving this problem:给出这个问题的部分:

For Each OLEobj In ThisWorkbook.Sheets("SheetName").OLEObjects
    Set OLEobj = wsr.OLEObjects(OLEobj.Name)
    OLEobj.Verb xlVerbOpen
    Application.Wait (Now + TimeValue("0:00:05"))
    'Sleep 5000
    Set wbR = ActiveWorkbook
    Exit For
Next OLEobj

Using .Verb xlVerbOpen can be dicey to get the "active" application.使用.Verb xlVerbOpen获得“活动”应用程序可能很冒险。

Activate (start/open) the object and use the OLEFormat.Object.Object to get the workbook object. Activate (start/open)对象并使用OLEFormat.Object.Object来获取工作簿对象。

Is this what you are trying?这是你正在尝试的吗?

Option Explicit

Sub Sample()
    Dim ws As Worksheet
    Dim shp As Shape
    Dim wb As Object

    '~~> Change this to the relevant sheet where the excel file is embedded
    Set ws = Sheet1

    '~~> Change this to the relevant object name
    Set shp = ws.Shapes("Object 1") ' OLEobj.Name? from your code?

    '~~> Activate it (Open it)
    shp.OLEFormat.Activate

    '~~> Get the workbook object
    Set wb = shp.OLEFormat.Object.Object

    With wb
        '
        '~~> Work with the workbook object here
        '

        MsgBox .Worksheets.Count
    End With
End Sub

Following your suggestion I have changed my code as seen below and it does work as a charm.按照您的建议,我更改了我的代码,如下所示,它确实很有魅力。 Thank you so much for your help!!非常感谢你的帮助!!

For Each OLEobj In ThisWorkbook.Sheets("Ratios").OLEObjects
    Set OLEobj = wsr.OLEObjects(OLEobj.Name)
    'OLEobj.Verb xlVerbOpen
    OLEobj.Activate
    **Set wbR = OLEobj.Object**  ' New line that solves the issue.
    Exit For
Next OLEobj

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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