在新的Excel实例中打开Excel OLEObject

时间:2019-03-16 20:47:15

标签: excel vba

我刚刚学会了通过以下VBA-Excel代码打开以编程方式嵌入的OLEObject:

mySheet.OLEObjects(myName).Verb xlVerbOpen

但是,如果“ myName”对应于Excel对象,则在运行程序的同一Excel实例中打开Excel文件。由于当时有几个打开的表单,我希望在一个新的Excel实例中打开该对象(而不是在表单后面,因为它正在发生)。这可能吗?我该怎么办?提前谢谢。

2 个答案:

答案 0 :(得分:0)

您可以在代码中创建新的Excel实例(在下面的示例中,xlApp),然后在接下来的操作中引用该实例(但是,只有在使用链接创建OLEObject的情况下,此实例才有效)

Dim xlApp As New Excel.Application, xlWb As Workbook

Set xlApp = CreateObject("Excel.Application")
xlApp.Visible = True 'Make new instance visible (by default it's not visible)
Set xlWb = xlApp.Workbooks.Open(Filename) ' Filename is path to the linked workbook

如果未链接OLEObject,则在新Excel实例中打开的唯一方法是使用主excel文件打开,这不是您想要的:

xlApp.Workbooks.Open(workbookpath).Worksheets("mySheet").OLEObjects(myName).Verb xlVerbOpen

答案 1 :(得分:0)

按照Richard的建议,请参见下面构建的代码,该代码使我能够通过VBA在新Excel实例中的新工作簿中打开嵌入式excel对象:

                Dim xlApp As excel.Application
                Dim xlWb  As Workbook
                Dim mySheet As Worksheet
                Dim myName as String

                Set mySheet = Sheets("write sheet name")
                Set myName = Sheets("write object name")

                ThisWorkbook.Sheets(mySheet).OLEObjects(myName).Copy
                Set xlApp = New excel.Application
                xlApp.Visible = True
                Set xlWb = xlApp.Workbooks.Add
                xlWb.Sheets(1).Paste
                xlWb.Sheets(1).OLEObjects(myName).Verb xlVerbOpen

致谢