Workbooks.Open returns different file than Filename - vba

I am having the strangest problem. I was writing the below code on my laptop the other day and it worked fine. Now, I am testing it on my desktop and it's stopped working.
First, here's 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 solver is an add in, and it gets loaded in the new application upon creating it... but how does it perform this switcheroo? I can still get to the correct file, but I don't want to risk it on the coincidence that there is only 1 file in my Application object (or that the first file is the one I loaded)
Additional Info
I am calling executing this macro from within an excel instance and I wish to open a separate excel instance and then open particular workbook ("C:\myFile.xlsx") inside that other instance.
The key problem I'm having is that when I open the other instance and then add the workbook and set it to my oWb variable... somehow, when I later call that oWb variable it refers to something different from what I had set it to.
'This is how it makes me feel:
Dim x As Integer
x = 5
Debug.Print x
' 12

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

Related

VBA open workbook, exits code

I try to open a workbook of the type '.xlsm' using
Private Function readFiles(ByVal lv_path As String, ByRef lx_wrkShDes As Worksheet)
'On Error GoTo ErrorHandling
Dim lx_objectExcel As New Excel.Application
Dim lx_wrkBkSrc As Workbook
Dim lx_wrkShSrc As Worksheet
Dim lx_shrPathObj As Object
Dim lv_shrPath As String
Set lx_shrPathObj = CreateObject("scripting.filesystemobject")
lv_shrPath = Replace(lx_shrPathObj.GetFile(lv_path).ShortPath, mv_longFilePathHelper, "")
Set lx_wrkBkSrc = Workbooks.Open(Filename:=lv_shrPath, ReadOnly:=True)
'Using lx_objectExcel.Workbooks.Open WORKS but not Workbooks.Open
'lx_objectExcel.Workbooks.Open(Filename:=lv_shrPath, ReadOnly:=True)
If Not Library.DoesSheetExist(lx_wrkBkSrc, mv_workSheetName) Then
GoTo ErrorHandling
End If
Set lx_wrkShSrc = lx_wrkBkSrc.Sheets(mv_workSheetName)
'Rest of the function
End Function
It opens the workbook and exits the VBA code immediately.
I tried this https://support.microsoft.com/en-us/help/555263, but same results.
It does not exit if I use new instance of Excel using
lx_objectExcel.Workbook.open('path')
I do not want to use a new instance as paste special is not suitable with new instance and opening 100s of Workbooks this way consumes lot of time.
Replace:
Workbook.open('path')
With
Workbooks.Open("PathName")
Referring to the Workbook.Open method, the correct syntax for your action is the following
Workbooks.Open("WorkbookPath")
The following code totally works for me
Dim targetWorkbook As Workbook
Set targetWorkbook = Workbooks.Open("YourWorkbookPath")
You are not using it properly. If this still doesn't work, make sure to send the correct path for your file.
tried this code with 2 xlsm files (MASTER and SLAVE) and it works fine form me. Office 2013
Dim sText As String
Dim objWB As Excel.Workbook
sText = ThisWorkbook.Worksheets("Sheet1").Range("A1").Value
Set objWB = Application.Workbooks.Open(ThisWorkbook.Path & "\SLAVE.XLSM")
objWB.Worksheets("Sheet1").Range("A1").Value = sText
MsgBox "DONE!"

VBA on open workbook exits code? [duplicate]

I try to open a workbook of the type '.xlsm' using
Private Function readFiles(ByVal lv_path As String, ByRef lx_wrkShDes As Worksheet)
'On Error GoTo ErrorHandling
Dim lx_objectExcel As New Excel.Application
Dim lx_wrkBkSrc As Workbook
Dim lx_wrkShSrc As Worksheet
Dim lx_shrPathObj As Object
Dim lv_shrPath As String
Set lx_shrPathObj = CreateObject("scripting.filesystemobject")
lv_shrPath = Replace(lx_shrPathObj.GetFile(lv_path).ShortPath, mv_longFilePathHelper, "")
Set lx_wrkBkSrc = Workbooks.Open(Filename:=lv_shrPath, ReadOnly:=True)
'Using lx_objectExcel.Workbooks.Open WORKS but not Workbooks.Open
'lx_objectExcel.Workbooks.Open(Filename:=lv_shrPath, ReadOnly:=True)
If Not Library.DoesSheetExist(lx_wrkBkSrc, mv_workSheetName) Then
GoTo ErrorHandling
End If
Set lx_wrkShSrc = lx_wrkBkSrc.Sheets(mv_workSheetName)
'Rest of the function
End Function
It opens the workbook and exits the VBA code immediately.
I tried this https://support.microsoft.com/en-us/help/555263, but same results.
It does not exit if I use new instance of Excel using
lx_objectExcel.Workbook.open('path')
I do not want to use a new instance as paste special is not suitable with new instance and opening 100s of Workbooks this way consumes lot of time.
Replace:
Workbook.open('path')
With
Workbooks.Open("PathName")
Referring to the Workbook.Open method, the correct syntax for your action is the following
Workbooks.Open("WorkbookPath")
The following code totally works for me
Dim targetWorkbook As Workbook
Set targetWorkbook = Workbooks.Open("YourWorkbookPath")
You are not using it properly. If this still doesn't work, make sure to send the correct path for your file.
tried this code with 2 xlsm files (MASTER and SLAVE) and it works fine form me. Office 2013
Dim sText As String
Dim objWB As Excel.Workbook
sText = ThisWorkbook.Worksheets("Sheet1").Range("A1").Value
Set objWB = Application.Workbooks.Open(ThisWorkbook.Path & "\SLAVE.XLSM")
objWB.Worksheets("Sheet1").Range("A1").Value = sText
MsgBox "DONE!"

Excel 2016 crashed when vba use saveas method on new application

I try to use Workbook.SaveAs method to save a new workbook with a specific name. I found it runs fine within the Application which the code run on. But caused excel crash with a new application. What's the problem?
Excel 2016 on Windows 10 Pro.
Codes below:
Sub test()
Dim this_app As Application
Set this_app = Application
Dim new_app As Application
Set new_app = New Application
new_app.Visible = True
Dim wb As Workbook
Set wb = this_app.Workbooks.Add
wb.SaveAs Filename:="new_file_name1"
'above SaveAs succeed
Set wb = new_app.Workbooks.Add
wb.SaveAs Filename:="new_file_name2"
'above SaveAs cause excel crash
End Sub
If I use SaveCopyAs method (code below), both is fine. But I still want to know why SaveAs caused Excel crashed.
Sub test()
Dim this_app As Application
Set this_app = Application
Dim new_app As Application
Set new_app = New Application
new_app.Visible = True
Dim wb As Workbook
Set wb = this_app.Workbooks.Add
wb.SaveCopyAs Filename:="new_file_name1.xlsx"
'above SaveCopyAs succeed
Set wb = new_app.Workbooks.Add
wb.SaveCopyAs Filename:="new_file_name2.xlsx"
'above SaveCopyAs also succeed
End Sub
The following works for me (Excel 2013):
Option Explicit
Sub TestMe()
Dim this_app As Application
Set this_app = Application
Dim new_app As Application
Set new_app = New Application
new_app.Visible = True
Dim wb As Workbook
Set wb = this_app.Workbooks.Add
wb.SaveAs Filename:="new_file_name11"
'above SaveAs sucessed
Set wb = new_app.Workbooks.Add
wb.SaveAs Filename:="new_file_name22"
'above SaveAs cause excel crash
End Sub
I suppose that your problem was in app.Visible or that you already had a file named new_file_name2, thus it crashed. Try changing the files and always add Option Explicit on the top of your code.

Deleting empty worksheets

I'm trying to write a code to delete empty worksheets in a workbook. So far I have been able to delete worksheets starting at the highest to the lowest using the code:
Dim i As Integer
Dim objExcel As Object = CreateObject("Excel.Application")
objExcel.Visible = True
objExcel.DisplayAlerts = False
Dim objWorkbook As Excel.Workbook = objExcel.Workbooks.Open(TextBox1.Text)
i = objWorkbook.Worksheets.Count
Do Until i = 2
objWorkbook.Worksheets(1).Delete()
i = i - 1
Loop
I had a look on the internet, but didn't find something that can be useful. Can anyone help me by guiding me to the right direction where I can obtain information on how to detect for empty worksheets in a single workbook using VB.net only.
Thank You
This should do the trick in vb.net
Private Sub DeleteBlankWorksheets(xlWorkBook As Excel.Workbook)
For i As Integer = xlWorkBook.Worksheets.Count To 1 Step -1
Dim ws As Excel.Worksheet = CType(xlWorkBook.Worksheets(i), Excel.Worksheet)
If Convert.ToInt64(ws.UsedRange.CountLarge) <= 1 Then
ws.Delete()
End If
Next
End Sub
Replace your entire loop with a call to this function, passing your objWorkBook object as the parameter.
Dim objExcel As Object = CreateObject("Excel.Application")
objExcel.Visible = True
objExcel.DisplayAlerts = False
Dim objWorkbook As Excel.Workbook = objExcel.Workbooks.Open(TextBox1.Text)
DeleteBlankWorksheets(objWorkbook)
'Add this to save the file
objWorkbook.Save()
objWorkbook.Close() 'closes the files
'If you have trouble with the file object being still opened, meaning you can see the EXCEL.exe in the task manager then add the following code
For Each instance As Process In Process.GetProcesses
If InStr(instance.MainWindowTitle, Textbox1.Text) <> 0 Then p.Kill()
Next
NOTE: It is better to make sure to dispose of all of your excel objects (applications, workbooks, worksheets, etc) than to kill processes. This will ensure all data is preserved as intended without side effects. If you find you have extra excel.exe instances running, make sure to double check everything is disposed and released properly.
This will do the job
Sub DeleteBlankWs()
Dim ws As Worksheet
For Each ws In Worksheets
If WorksheetFunction.CountA(ws.Cells) = 0 Then
Application.DisplayAlerts = False
ws.Delete
Application.DisplayAlerts = True
End If
Next ws
End Sub
I created an excel with 5 sheets, sheet 2 and 4 are empty, then I edited a micro and run it (F5 key or the green play icon)...

Opening a workbook with VBA/macro is making it read only?

I would like my code to open a workbook (always the same one), detect the first free row, write to just two cells in that row, and then save/close the workbook. This seems like a simple problem, but the macro seems to be opening a copy of the file, and then locking it for editing.
Can you see any errors in my open code? I know that the file opens and that the row search works, but then it 1. never writes to the cells, and 2. locks the file.
Function WriteToMaster(Num, Path) As Boolean
'Declare variables
Dim xlApp As Excel.Application
Dim wb As Workbook
Dim ws As Worksheet
Dim infoLoc As Long
Set xlApp = New Excel.Application
'Specifies where the Master Move Key is stored
Set wb = xlApp.Workbooks.Open("DOC LOCATION")
Set ws = wb.Worksheets("Sheet1")
'Loop through cells, looking for an empty one, and set that to the loan number
infoLoc = firstBlankRow(ws)
MsgBox "First blank row is " & infoLoc & ". Num is " & Num
ws.Cells(infoLoc, 1).Value = Num
ws.Cells(infoLoc, 2).Value = Path
'Save, close, and quit
wb.Save
wb.Close
xlApp.Quit
'Resets the variables
Set ws = Nothing
Set wb = Nothing
Set xlApp = Nothing
'pieces of function from http://p2p.wrox.com/vb-how/30-read-write-excel-file-using-vb6.html
End Function
Thank you again, stackoverflow <3
Do you need to open a new excel app just to open a workbook?
Can't you just do something like this:
Sub Macro1()
Dim wkb As Workbook
Workbooks.Open Filename:="\User Documents$\bob\My Documents\workbook_open_example.xlsx"
Set wkb = Workbooks("workbook_open_example.xlsx")
End Sub