Workbooks.Open returns a different file than Filename

I have the strangest problem. The other day, I wrote the code below on my laptop, and it worked fine. Now I am testing it on my desktop and it stops working.

First, here is my code

Dim oApp As Application Dim oWb As Workbook Set oApp = New Application oApp.Visible = True Set oWb = oApp.Workbooks.Open(Filename:="C:\myFile.xlsx", ReadOnly:=True) debug.print oWb.name 'returns "SOLVER.XLAM" ' "SOLVER.XLAM" is not "myFile.xlsx' debug.print oApp.Workbooks.Count 'returns 1 debug.print oApp.Workbooks(1).name 'returns "myFile.xlsx" 

Now I know that the solver is an addition, and it loads into the new application when it is created ... but how does it execute this switch? I can still get to the desired file, but I do not want to risk it by coincidence that in my application object there is only 1 file (or the first file is the one I downloaded)

Additional Information

I am invoking the execution of this macro from an excel instance, and I want to open a separate excel instance and then open a specific workbook ( "C:\myFile.xlsx" ) inside that other instance.

The main problem I am facing is that when I open another instance and then add the book and set it in my oWb variable ... somehow, when I later call this variable oWb, it refers to something different from what i installed it.

 'This is how it makes me feel: Dim x As Integer x = 5 Debug.Print x ' 12 
+5
vba excel-vba excel excel-2010
source share
2 answers

I think that if you just refine your code a bit to make sure that you are doing exactly what you want, you will be fine. Since it is unclear whether you are calling the code from Excel or another MS Office application, I posted it below.

Run it if it is running 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 it if it is running in another program. I use early binding, but you can use the last binding if you want:

 Sub outsideXL() 'make sure Microsoft Excel XX 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 
+3
source share

I found this (which worked in 2007):

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

need to write

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

for 2010

+1
source share

All Articles