Workbooks.Open returns different file than Filename

久未见 提交于 2019-12-04 07:03:44

I think if you just refine your code a bit to ensure you are doing exactly what you want, you will be fine. Since it's unclear whether you are calling the code from within Excel or another MS Office Application, I placed to subs below.

Run this if running it in Excel:

Option Explicit

Sub insideXL()

Dim oWb As Workbook
Set oWb = Workbooks.Open("C:\myFile.xlsx", ReadOnly:=True)

Debug.Print oWb.Name
Debug.Print Workbooks.Count
Debug.Print Workbooks(1).Name

oWb.Close false

Set oWb = Nothing    

End Sub

Run this if running in another program. I use early binding, but you could use late binding as well, if you wish:

Sub outsideXL()
'make sure Microsoft Excel X.X Object Library is checked in Tools > References

Dim oApp As Excel.Application
Set oApp = New Excel.Application

Dim oWb As Excel.Workbook
Set oWb = oApp.Workbooks.Open("C:\myFile.xlsx", ReadOnly:=True)

oApp.Visible = True

Debug.Print oWb.Name
Debug.Print Workbooks.Count
Debug.Print Workbooks(1).Name

oWb.Close = True
Set oWb = Nothing
Set oApp = Nothing    

End Sub

I found that this (which worked in 2007):

wb = excel.Workbooks.Open(filename, False, True)

needs to be written

excel.Workbooks.Open(filename, False, True)
wb = excel.ActiveWorkbook

for 2010

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!