Workbook.Open, closes original workbook?

Beyond_avarice

Board Regular
Joined
Nov 13, 2012
Messages
195
Office Version
  1. 2007
Platform
  1. Windows
Hello I've peeked into this website(and others) for years. I'm finally getting around to learning how to implement VBA. I have made a solution (by copying scripts available and learning how to write portions of it myself :) , code below) to automate collecting information from an .XLS file and appending it to the last row of information in a master workbook. This code works under the following situations:

  • On workbooks with macro(ie saved), in XL07.
  • As an addin on saved workbooks, in XL07.
  • As a Personal macro on saved workbooks, in XL07.
  • With dual monitors on a saved workbooks, in XL07.
  • Active unsaved workbooks that are not "Book1".
This code does not appear to work under the following situations:

  • On a new workbook ("Book1"), using either the personal macro or the addin, in XL07 or XL10.
  • On dual monitors with XL10???
When I attempt to run this script in XL07 with a new workbook("Book1"), with either the personal macro or addin, the original workbook is closed down at the point the script attempts to open a new workbook(.xls file selected). The code attempts to copy information from the second workbooks and paste it to the original workbook, but since the original closes; the code stalls and asks for an object (ie wb1- original activeworkbook).

In XL10, the new workbook opens then the code just stalls and I cannot get an error to throw. The original saved workbook is still open??

Now if I open a new instance of Xl07 ("Book1"), then I close the workbook(leaving the application open) and open a new workbook ("Book2"), the personal macro and addin work??? I do not have to save Book2, Book3, etc. There just seems to be something about Book1 that does not permit the personal macro or addin to work?

If I save Book1, then everything works(XL07)???

Some of my coworkers have XL2010 and Dual Monitors, I have attempted to turn off the second monitor and the problem still exists(details above).

I cannot continually bug them for access to their XL10 so I would at minimum like to focus on why Workbooks.Open() appears to be the problem. I have stepped through the code dozens of times and the problem occurs at the
HTML:
Set wb2 = Workbooks.Open(Ret1)

This is the point that the activeworkbook("wb1") closes(XL07) or the new workbook opens and everything stalls (XL10).

I am on my company computer and I believe my Office applications are unit specific and not on the Citrix network.

I have made sure that the hotkeys do not include "shift", and the problem is still there.

Below is the full code, I am hoping someone can shed some light on my problem. Thank you in advance.

HTML:
Sub Collect_BG_Files()

Application.ScreenUpdating = False
    
'Identify active workbook and workbook to open and select information from.

Dim wb1 As Workbook, wb2 As Workbook
Dim Ret1
Dim ePoint As Variant 'define the endpoint to append to.

Set wb1 = ActiveWorkbook

   If Range("A2") = "" Then
          ePoint = Range("A2").Address
    Else: Range("A2").Select
        ActiveCell.End(xlDown).Select
        ePoint = ActiveCell.Offset(1, 0).Address
    End If
        
    '~~> Get the first File
    Ret1 = Application.GetOpenFilename("Excel Files (*.xls*), *.xls*", _
    , "Please select first file")
    If Ret1 = False Then Exit Sub

Set wb2 = Workbooks.Open(Ret1)
    If Range("A3").Value = "" Then
    
        wb2.Sheets(1).Range("A2:K2").Select
        Selection.Copy wb1.Sheets(1).Range(ePoint)
        wb2.Close SaveChanges:=False
    Else
        wb2.Sheets(1).Range("A2:K2").Select
        Range(Selection, Selection.End(xlDown)).Copy wb1.Sheets(1).Range(ePoint)
        
        wb2.Close SaveChanges:=False
    End If
    
    Set wb2 = Nothing
    Set wb1 = Nothing
    
Application.ScreenUpdating = True
    
End Sub
 
Last edited:

Excel Facts

How to change case of text in Excel?
Use =UPPER() for upper case, =LOWER() for lower case, and =PROPER() for proper case. PROPER won't capitalize second c in Mccartney
I'm confused, but Workbook.Open doesn't close original workbook, opens a wb, this wb becomes active wb, when you close active wb, original workbook becomes active.
 
Upvote 0
If you physically add a new workbook (ie using Ctrl+N in the Excel interface) rather than simply accepting the empty workbook that appears when you start Excel, does this problem still exhibit itself?
 
Upvote 0
It looks suspicious using Set wb1 = ActiveWorkbook in this code. There might be some confusion about what workbook is active when that line executes. Also you never want to use unqualified references in any code where you use more than one workbook (i.e. instead of Range you want Workbooks(1).Worksheets(1).Range).

Not sure but removing selection and qualifying everything might help:
(UNTESTED - EXPECT ERRORS)
Code:
[COLOR="Navy"]Sub[/COLOR] Collect_BG_Files()
[COLOR="Navy"]Dim[/COLOR] wb1 [COLOR="Navy"]As[/COLOR] Workbook, wb2 [COLOR="Navy"]As[/COLOR] Workbook
[COLOR="Navy"]Dim[/COLOR] Ret1
[COLOR="Navy"]Dim[/COLOR] ePoint [COLOR="Navy"]As[/COLOR] Range [COLOR="SeaGreen"]'define the endpoint to append to.[/COLOR]

    [COLOR="SeaGreen"]'Identify active workbook and set endpoint range[/COLOR]
    [COLOR="Navy"]Set[/COLOR] wb1 = ActiveWorkbook
    [COLOR="Navy"]With[/COLOR] wb1
       [COLOR="Navy"]If[/COLOR] .Range("A2") = "" [COLOR="Navy"]Then[/COLOR]
            [COLOR="Navy"]Set[/COLOR] ePoint = .Range("A2")
        [COLOR="Navy"]Else[/COLOR]
            [COLOR="Navy"]Set[/COLOR] ePoint = .Range("A2").End(xlDown)
            [COLOR="Navy"]If[/COLOR] ePoint.Row <> Rows.Count [COLOR="Navy"]Then[/COLOR]
                [COLOR="Navy"]Set[/COLOR] ePoint = ePoint.Offset(1, 0)
            [COLOR="Navy"]Else[/COLOR]
                MsgBox "Error: Sheet Full."
                [COLOR="Navy"]Exit[/COLOR] [COLOR="Navy"]Sub[/COLOR]
            [COLOR="Navy"]End[/COLOR] [COLOR="Navy"]If[/COLOR]
        [COLOR="Navy"]End[/COLOR] [COLOR="Navy"]If[/COLOR]
    [COLOR="Navy"]End[/COLOR] [COLOR="Navy"]With[/COLOR]

    [COLOR="SeaGreen"]'Workbook to open and select information from[/COLOR]
    Ret1 = Application.GetOpenFilename("Excel Files (*.xls*), *.xls*", _
    , "Please select first file")
    [COLOR="Navy"]If[/COLOR] Ret1 = False [COLOR="Navy"]Then[/COLOR] [COLOR="Navy"]Exit[/COLOR] [COLOR="Navy"]Sub[/COLOR]
    [COLOR="Navy"]Set[/COLOR] wb2 = Workbooks.Open(Ret1)

    [COLOR="SeaGreen"]'Copy information to endpoint[/COLOR]
    [COLOR="Navy"]With[/COLOR] wb2.Sheets(1)
        [COLOR="Navy"]If[/COLOR] .Range("A3").Value = "" [COLOR="Navy"]Then[/COLOR]
            .Range("A2:K2").Copy Destination:=ePoint
        [COLOR="Navy"]Else[/COLOR]
            .Range(.Range("A2:K2"), .Range("A2:K2").End(xlDown)).Copy Destination:=ePoint
        [COLOR="Navy"]End[/COLOR] [COLOR="Navy"]If[/COLOR]
    [COLOR="Navy"]End[/COLOR] [COLOR="Navy"]With[/COLOR]
    wb2.Close SaveChanges:=False
    
[COLOR="Navy"]End[/COLOR] [COLOR="Navy"]Sub[/COLOR]

I wouldn't expect code to work on unsaved Workbooks (Book1) - these have some unusual properties, such as not having a filepath (and you couldn't select them from a getopenfiledialog so not sure why you would be using this code on that kind of workbook anyway.
 
Upvote 0
It looks suspicious using Set wb1 = ActiveWorkbook in this code. There might be some confusion about what workbook is active when that line executes. Also you never want to use unqualified references in any code where you use more than one workbook (i.e. instead of Range you want Workbooks(1).Worksheets(1).Range).

Not sure but removing selection and qualifying everything might help:
(UNTESTED - EXPECT ERRORS)
Code:
I wouldn't expect code to work on unsaved Workbooks (Book1) - these have some unusual properties, such as not having a filepath (and you couldn't select them from a getopenfiledialog so not sure why you would be using this code on that kind of workbook anyway.[/QUOTE]

I'm learning so these are good things to pick. Use "Qualified references." I corrected your code to reference Sheet(1) of wb1, as that was throwing an error. I know I need to learn how to kick the habit of selecting and Activecells and I was actually able to reduce some of it before posting. I will get better, I promise.

After my initial post I attempted some further research and came upon "ActiveWorkbook.Saved = False". I'm afraid I do not recall where I got it so I apologize for not giving credit. Setting this piece after my "Set wb1 = ActiveWorkbook" eliminated the problem with needing to save "Book1".

My intent to have "Set wb2 = Workbook.Open(ret1)" work on a new unsaved workbook; is for future projects, where I may have a master file that I want to collect information from to run testings or whatever. I initially identified the problem ("Book1") when I was just trying to solve the error and I set the code up as a personal macro, to use on new workbooks.

I thank you for giving me an example of how to write the script without "selections" and "activecell" references. I will use this as a study aid for my own development. I however tried to implement your revisions and while I found success with XL07, I was not successful with my coworkers XL10 (dual monitors). I am still having the same problem of wb2 opening and the code stalls.

I am hoping someone, that has XL10(single monitor), could attempt to implement either your code or mine and identify if the problem still exists. If it does; I was skeptical but I would have to suspect something with XL10 is causing the problem.

Thank you for your help.
 
Upvote 0
Is it possible the workbook is already open when the user selects the file name?
 
Upvote 0
Hmm. I discovered a bug in your code:
Code:
If Ret1 = False Then Exit Sub
This should be:
Code:
If Ret1 = "False" Then Exit Sub


You could trap the error of trying to open the workbook if it is already open (or any other errors opening workbooks). I'd push it out to a smallish function. And since I don't like to close workbooks on users who had them open, we can try to capture that bit of data too.


Code:
[COLOR="Navy"]Sub[/COLOR] TestIt()
[COLOR="Navy"]Dim[/COLOR] wb [COLOR="Navy"]As[/COLOR] Workbook
[COLOR="Navy"]Dim[/COLOR] Workbook_Already_Open [COLOR="Navy"]As[/COLOR] [COLOR="Navy"]Boolean[/COLOR]
[COLOR="Navy"]Dim[/COLOR] arg [COLOR="Navy"]As[/COLOR] [COLOR="Navy"]Boolean[/COLOR]

    [COLOR="SeaGreen"]'//Set Workbook Reference to a workbook the user chooses[/COLOR]
    [COLOR="Navy"]Set[/COLOR] wb = GetExcelWorkbook(arg)
    [COLOR="Navy"]If[/COLOR] arg = True [COLOR="Navy"]Then[/COLOR]
        Workbook_Already_Open = True [COLOR="SeaGreen"]'//Since the workbook was open, we won't close it at the end[/COLOR]
    [COLOR="Navy"]End[/COLOR] [COLOR="Navy"]If[/COLOR]

    [COLOR="Navy"]If[/COLOR] wb [COLOR="Navy"]Is[/COLOR] [COLOR="Navy"]Nothing[/COLOR] [COLOR="Navy"]Then[/COLOR]
        [COLOR="SeaGreen"]'//Exit or take other action - we didn't get the workbook open[/COLOR]
    [COLOR="Navy"]Else[/COLOR]
        [COLOR="SeaGreen"]'//All is well[/COLOR]
        MsgBox wb.Name
        [COLOR="Navy"]If[/COLOR] [COLOR="Navy"]Not[/COLOR] Workbook_Already_Open [COLOR="Navy"]Then[/COLOR]
            wb.Close False
        [COLOR="Navy"]End[/COLOR] [COLOR="Navy"]If[/COLOR]
    [COLOR="Navy"]End[/COLOR] [COLOR="Navy"]If[/COLOR]


[COLOR="Navy"]End[/COLOR] [COLOR="Navy"]Sub[/COLOR]
[COLOR="Navy"]Function[/COLOR] GetExcelWorkbook(Optional [COLOR="Navy"]ByRef[/COLOR] OpenState [COLOR="Navy"]As[/COLOR] Boolean) [COLOR="Navy"]As[/COLOR] Workbook
[COLOR="Navy"]Dim[/COLOR] sPath [COLOR="Navy"]As[/COLOR] [COLOR="Navy"]String[/COLOR]

    [COLOR="Navy"]On[/COLOR] [COLOR="Navy"]Error[/COLOR] [COLOR="Navy"]Resume[/COLOR] [COLOR="Navy"]Next[/COLOR]
    
    [COLOR="SeaGreen"]'//Get File Name[/COLOR]
    sPath = Application.GetOpenFilename("Excel Files (*.xls*), *.xls*", _
    , "Please select first file")
    
    [COLOR="Navy"]If[/COLOR] sPath = "False" [COLOR="Navy"]Then[/COLOR]
        [COLOR="Navy"]Exit[/COLOR] [COLOR="Navy"]Function[/COLOR]
    
    [COLOR="Navy"]Else[/COLOR]
        [COLOR="SeaGreen"]'//Attempt to find the open workbook[/COLOR]
        [COLOR="Navy"]Set[/COLOR] GetExcelWorkbook = Workbooks(CreateObject("Scripting.FileSystemObject").GetFileName(sPath))
        [COLOR="SeaGreen"]'//Otherwise open the workbook[/COLOR]
        [COLOR="Navy"]If[/COLOR] [COLOR="Navy"]Not[/COLOR] GetExcelWorkbook [COLOR="Navy"]Is[/COLOR] [COLOR="Navy"]Nothing[/COLOR] [COLOR="Navy"]Then[/COLOR]
            OpenState = True
        [COLOR="Navy"]Else[/COLOR]
            [COLOR="Navy"]Set[/COLOR] GetExcelWorkbook = Workbooks.Open(sPath)
        [COLOR="Navy"]End[/COLOR] [COLOR="Navy"]If[/COLOR]
        
    [COLOR="Navy"]End[/COLOR] [COLOR="Navy"]If[/COLOR]
    
[COLOR="Navy"]End[/COLOR] [COLOR="Navy"]Function[/COLOR]

By the way your code has nothing in it that would give excel any difficulties that I can see, XL2010 or not. It might be a red herring with the version number (maybe something else is going on that you haven't though of yet or is specific to that user or that machine, their excel settings, or even the workbook they are trying to open).
 
Last edited:
Upvote 0

Forum statistics

Threads
1,214,822
Messages
6,121,770
Members
449,049
Latest member
greyangel23

We've detected that you are using an adblocker.

We have a great community of people providing Excel help here, but the hosting costs are enormous. You can help keep this site running by allowing ads on MrExcel.com.
Allow Ads at MrExcel

Which adblocker are you using?

Disable AdBlock

Follow these easy steps to disable AdBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the icon in the browser’s toolbar.
2)Click on the "Pause on this site" option.
Go back

Disable AdBlock Plus

Follow these easy steps to disable AdBlock Plus

1)Click on the icon in the browser’s toolbar.
2)Click on the toggle to disable it for "mrexcel.com".
Go back

Disable uBlock Origin

Follow these easy steps to disable uBlock Origin

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back

Disable uBlock

Follow these easy steps to disable uBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back
Back
Top