+ Reply to Thread
Results 1 to 9 of 9

Capturing open workbook as variable?

Hybrid View

  1. #1
    Registered User
    Join Date
    09-23-2013
    Location
    Gold Coast, Australia
    MS-Off Ver
    2010
    Posts
    50

    Capturing open workbook as variable?

    I've discovered that the code I have for pulling a template worksheet into an open workbook runs into problems that results in the code ThisWorkbook referencing the template, and not the open workbook.

       pvt_obj_Workbook.Worksheets("Ten").Copy Before:=ThisWorkbook.Worksheets(1)
    I'm trying to capture the open workbook name into a variable to try and get my macro to work properly. The target (open workbook) will have multiple locations and names, but the template worksheet will be stored in a static location.


    Public Sub copyNetContentsFiveWorksheet()
    On Error Resume Next
    
    '#
    '# declare private variables
    '#
       Dim pvt_obj_Workbook As Excel.Workbook
       Dim pvt_obj_TargetWorkbook As Excel.Workbook
       Dim pvt_str_WorksheetName As String
    
       Const pvt_cstr_TemplateWorkbook As String = "P:\QC Sheets\PRO-B 4.4 FM 03 04 Line 4&5 QC sheets.xlsm"
       
       pvt_obj_TargetWorkbook = ThisWorkbook
       
    '#
    '# prompt the user for the name to be given to the new worksheet after
    '# the worksheet has been imported
    '#
       pvt_str_WorksheetName = InputBox("Please enter date and shift for new sheet" & Chr(13) & _
                                        "eg.24-02-13-D or 24-02-13-N1." & Chr(13) & "DO NOT USE SLASHES ( \ or / )", "Add New Sheet")
       If Len(pvt_str_WorksheetName & "") = 0 Then
          Exit Sub
       End If
       
    '#
    '# freeze application user interface for performance reasons and suppress any warnings issued
    '#
       Application.ScreenUpdating = False
       Application.DisplayAlerts = False
       
    '#
    '# open the workbook holding the template worksheet to copy - note that the constant variable must hold the full
    '# path and name of the workbook, for example C:\TEMP\TEMPLATE.XLSX
    '#
       Set pvt_obj_Workbook = Workbooks.Open(pvt_cstr_TemplateWorkbook)
       
       If pvt_obj_Workbook Is Nothing Then
          MsgBox "Unable to open the template workbook at " & pvt_cstr_TemplateWorkbook, vbCritical, "Error message"
          GoTo RoutineExit
       End If
       
    '#
    '# copy the template worksheet and insert the worksheet into the current workbook before the
    '# first existing worksheet
    '#
       pvt_obj_Workbook.Worksheets("Five").Copy Before:=pvt_obj_TargetWorkbook.Worksheets(1)
       If Err.Number = 9 Then
          MsgBox "No worksheet named Template exists in workbook " & pvt_cstr_TemplateWorkbook, vbCritical, "Error message"
          GoTo RoutineExit
       ElseIf Err.Number > 0 Then
          MsgBox "Error " & Err.Number & " " & Err.Description & " occured while attempting to copy the template worksheet", _
             vbCritical, "Error message"
          GoTo RoutineExit
       End If
       
    '#
    '# attempt to rename the newly inserted worksheet - if the rename fails, delete the copied template
    '# worksheet
    '#
       pvt_obj_TargetWorkbook.Worksheets(1).Name = pvt_str_WorksheetName
       If Err.Number > 0 Then
          MsgBox "An error occured while trying to rename the imported worksheet to " & pvt_str_WorksheetName, vbCritical, "Error message"
          ThisWorkbook.Worksheets(1).Delete
          GoTo RoutineExit
       End If
    
    RoutineExit:
       pvt_obj_Workbook.Close
       Application.ScreenUpdating = True
       Application.DisplayAlerts = True
       
    End Sub
    Any help would be greatly appreciated!
    Last edited by aaron.irvine; 10-10-2013 at 07:35 PM.

  2. #2
    Forum Contributor
    Join Date
    02-15-2010
    Location
    Everett, WA
    MS-Off Ver
    All versions; most components
    Posts
    188

    Re: Capturing open workbook as variable?

    ThisWorkbook should refer to the workbook in which the macro is running.

    You can declare a workbook variable:
    dim wb as workbook
    and then set that variable to a workbook using "Workbook.Open":
    set wb = Workbook.Open(<fullpathandworkbookname>)
    or you can select an already open workbook using its name

    set wb = Workbooks(<yourworkbookname>)

  3. #3
    Registered User
    Join Date
    09-23-2013
    Location
    Gold Coast, Australia
    MS-Off Ver
    2010
    Posts
    50

    Re: Capturing open workbook as variable?

    Thanks a lot gyclone!

    Is there the ability to set wb to equal the workbook the operator activates the macro button in?

    My concern is that the workbook names will change, and I need it to work autonomously without coding changes if possible.

    The biggest problem I see that I'm having is that the macro references the code in the source workbook after it's been imported into the target workbook. If I could get the macro to point to the local code (for want of the proper terminology) instead of pointing back to the source workbook, I think I would avoid having to create a variable.

  4. #4
    Forum Contributor
    Join Date
    02-15-2010
    Location
    Everett, WA
    MS-Off Ver
    All versions; most components
    Posts
    188

    Re: Capturing open workbook as variable?

    I'm afraid I'm not sure of the chronology of target vs source vs open. Nor am I sure of whether all the code exists in one workbook or whether you're trying to use one workbook to fire off code in another workbook. "ThisWorkbook", if used in the workbook with the macro button, should capture that workbook. You can use more than one workbook variable and assign each one as each additional workbook opens, as I showed above; just use different names:
    dim wbThis as workbook
    dim wbSource as workbook
    dim wbTarget as workbook
    Once each variable has been assigned, you can use them throughout the procedure.

    If you are using a macro in one workbook to launch a macro in another workbook, you can pass the necessary workbook names between the procedures, in the same manners you could if all the code was in the same workbook.

  5. #5
    Registered User
    Join Date
    09-23-2013
    Location
    Gold Coast, Australia
    MS-Off Ver
    2010
    Posts
    50

    Re: Capturing open workbook as variable?

    Sorry for not being clearer with the relationships of the files gyclone!

    target and open are the same file. This workbook is used by employees to capture data.

    Once the worksheet is full, they need to import a new worksheet template from the source workbook that is stored in another location.

    Ideally the macro code needs only exist in the target & open workbook - but each of the imported worksheets need to have an active macro button that will allow the employees to once again import another template worksheet from the source workbook.

    Everything works fine for the first import, but when I try to import a new worksheet from an imported worksheet it does not work. I believe my issue lies in where I am embedding the code, and how I am referencing it through the macros. I've tried embedding the code in the sheets, and in the workbook & neither worked for me.

    What I need is for the macro on an imported sheet to reference the code in the target & open workbook - and not reference back to the source workbook.

    I hope this makes it clearer? Thank you!

  6. #6
    Forum Contributor
    Join Date
    02-15-2010
    Location
    Everett, WA
    MS-Off Ver
    All versions; most components
    Posts
    188

    Re: Capturing open workbook as variable?

    Okay, I think I'm following, more or less.

    Scenario: You have two workbooks; one in which a user is entering data (Workbook1) and one which holds the data-entry template (Workbook2). When user clicks button on data-entry page in Workbook1, a template should be imported from Workbook2 into Workbook1. The newly-added template sheet added to Workbook1 needs a button which, when pressed, will fire off the same template-import macro as before, importing yet another copy of the template worksheet from Workbook2 into Workbook1.

    Assuming the above scenario is correct, I would create the new buttons on the new sheets at the time they are being imported. This should simplify things since you'll only need to reference the template workbook long enough to copy the sheet over. Once the sheet is copied over, you can close the template workbook, add the new button, and assign it to the same macro you used originally.

    I thought it would be clearer if I demonstrated with a fresh and very simple example. The code below covers the whole scenario (see attached workbooks for working example).
    Option Explicit
    
    Sub test()
    
        ' Variable to reference workbook holding macro (Starting Workbook)
        Dim wbThis As Workbook
        Set wbThis = ThisWorkbook
        
        ' Variable to reference template workbook
        Dim wbWithTemplate As Workbook
        Set wbWithTemplate = Workbooks.Open("C:\Users\Sean\Desktop\Template_Workbook.xlsm")
        
        ' Variable to reference template worksheet
        Dim wsTemplate As Worksheet
        Set wsTemplate = wbWithTemplate.Worksheets("Template_Worksheet")
        
        ' Copy template worksheet and paste into starting workbook
        wsTemplate.Copy Before:=wbThis.Worksheets(1)
        
        ' Turn off alerts so will close without prompting user
        Application.DisplayAlerts = False
        
        ' Close template workbook
        wbWithTemplate.Close
        
        ' Turn alerts back on
        Application.DisplayAlerts = True
        
        
        ' Variable to reference newly pasted sheet (in case you want to rename, etc.)
        Dim wsDestination As Worksheet
        Set wsDestination = ActiveSheet
        
       
        ' Add button
        ' Numbers in parentheses are location coordinates
        ActiveSheet.Buttons.Add(68.25, 56.25, 65.25, 32.25).Select
      
        ' Variable to reference button
        Dim btn As Button
        Set btn = ActiveSheet.Buttons(Selection.Name)
        
        ' Set button text to whatever you need
        btn.Caption = "Your Button Text"
        
        ' Deselect button
        wsDestination.Range("a1").Select
        
        
        ' Set macro to run when button is pressed
        btn.OnAction = "test"
        
        ' Clear objects
        Set btn = Nothing
        Set wsDestination = Nothing
        Set wsTemplate = Nothing
        Set wbWithTemplate = Nothing
        Set wbThis = Nothing
        
        
    End Sub

    Let me know if I've completely misunderstood or if you need more help plugging it into your situation.
    Attached Files Attached Files
    Last edited by gyclone; 10-10-2013 at 10:24 PM. Reason: Removed Redundant code

  7. #7
    Forum Contributor
    Join Date
    02-15-2010
    Location
    Everett, WA
    MS-Off Ver
    All versions; most components
    Posts
    188

    Re: Capturing open workbook as variable?

    Sorry, it's been a long day; you should make the following change:

     ' Copy template worksheet and paste into starting workbook
        wsTemplate.Copy Before:=wbThis.Worksheets(1)
        
        ' Turn off alerts so will close without prompting user
        Application.DisplayAlerts = False
        
        ' Close template workbook
        wbWithTemplate.Close
        
        ' Turn alerts back on
        Application.DisplayAlerts = True
        
        
        ' Variable to reference newly pasted sheet (in case you want to rename, etc.)
        Dim wsDestination As Worksheet
        Set wsDestination = ActiveSheet
    should be re-ordered, so we set the wsDestination variable right after we import the template sheet, just to be safe:

     ' Copy template worksheet and paste into starting workbook
        wsTemplate.Copy Before:=wbThis.Worksheets(1)
    
      ' Variable to reference newly pasted sheet (in case you want to rename, etc.)
        Dim wsDestination As Worksheet
        Set wsDestination = ActiveSheet
        
        ' Turn off alerts so will close without prompting user
        Application.DisplayAlerts = False
        
        ' Close template workbook
        wbWithTemplate.Close
        
        ' Turn alerts back on
        Application.DisplayAlerts = True

  8. #8
    Registered User
    Join Date
    09-23-2013
    Location
    Gold Coast, Australia
    MS-Off Ver
    2010
    Posts
    50

    Re: Capturing open workbook as variable?

    Please don't apologise mate! You've gone above and beyond to help me out here, thank you so much!

    I'm just tweaking the code now, I'll report back a little later to let you know how it goes. You hit the nail right on the head though for how everything is structured. I see my biggest mistake was embedding the code into the sheets and not into the button!

  9. #9
    Registered User
    Join Date
    02-23-2012
    Location
    Almaty, Kazakhstan
    MS-Off Ver
    Excel 2010
    Posts
    4

    Re: Capturing open workbook as variable?

    It does not matter. You are welcome.

+ Reply to Thread

Thread Information

Users Browsing this Thread

There are currently 1 users browsing this thread. (0 members and 1 guests)

Similar Threads

  1. How to copy values from one OPEN workbook (with variable file name) to another
    By Kitko in forum Excel Programming / VBA / Macros
    Replies: 8
    Last Post: 01-25-2013, 01:50 PM
  2. [SOLVED] Open Workbook, hidden, get cell data into a variable
    By Bruce Tjosvold in forum Excel Programming / VBA / Macros
    Replies: 3
    Last Post: 06-12-2012, 04:27 PM
  3. Open workbook as variable
    By Karen311261 in forum Excel Programming / VBA / Macros
    Replies: 5
    Last Post: 01-29-2012, 06:56 AM
  4. Assigning variable to open workbook
    By DavidBW in forum Excel Programming / VBA / Macros
    Replies: 5
    Last Post: 07-21-2011, 06:04 AM
  5. Open Workbook using a variable
    By AlanAnderson in forum Excel Programming / VBA / Macros
    Replies: 11
    Last Post: 06-29-2010, 07:51 AM

Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts

Search Engine Friendly URLs by vBSEO 3.6.0 RC 1