VBA - Switching between Workbooks

jhol4

Board Regular
Joined
Nov 18, 2002
Messages
71
Hi Guys,

I posted a question earlier about using a RefEdit to link to external workbooks, however it seems that this cannot be done.

So my new question is does anyone have a good way of alternating between workbooks using VBA where the name of the workbook is likely to change regularly.

I usually use Windows(filename.xls).activate, however if I don't know what the filename is, this becomes difficult.

Thanks in advance.
 
This question came up earlier today. This macro would go into the first workbook, which allow you to find out the name of, and activate, the "other workbook".

Sub Test1()
Dim wb As Workbook, x As String
For Each wb In Workbooks
If wb.Name <> ThisWorkbook.Name Then x = wb.Name
Next wb
MsgBox "The other open workbook is named " & x & "." & vbCrLf & _
"Click OK to activate it."
Workbooks(x).Activate
End Sub

Hi Tom,

I have read through all of your posts and I am very impressed with your VBA skill. I have a problem that doesn't quite fit with your solutions.

I have one workbook (REPORT), the name of which will never change, and will always be the workbook that I import data into and therefore tends to be the active workbook. I have to import (copy) data from a Busines Objects Excel export (EXPORT), the name of which is never the same (frustrating!).

What I would like to do is have a macro that copies data from the EXPORT into REPORT. I have tried the option of closing all documents except these two, using ActiveWindow.ActivatePrevious and then doing the copying and pasting but it is not ideal.

The ideal solution would be a userform of some sort that pops up with a list of all open excel workbooks which allows me to select one of them and assigns it a variable name. I can then refer to the EXPORT by variable name and do my copying and pasting.

I hope the above makes sense. If you could help you would be my hero :cool: ha!

Cheers,
Munni
 
Upvote 0
Thanks for your compliment. My goodness this thread has gotten quite a work-out over its 10 year life.

What you want to accomplish is definitely do-able. All that's unclear is how you determine the worksheet(s) in the export workbook, and if there are any particular columns or rows or ranges that you want to export from that workbook into your "IMPORT" workbook. I assume you would know what the export workbook name is when you see it. I realize the export workbook name will be different each time, but you would not confuse it with, say, the company budget workbook. So basically how do you want to identify the areas in the export workbook needing to be exported, and where exactly in the import workbook (the one that would host the code) would you want the export data to be imported.
 
Upvote 0
Thanks for your compliment. My goodness this thread has gotten quite a work-out over its 10 year life.

What you want to accomplish is definitely do-able. All that's unclear is how you determine the worksheet(s) in the export workbook, and if there are any particular columns or rows or ranges that you want to export from that workbook into your "IMPORT" workbook. I assume you would know what the export workbook name is when you see it. I realize the export workbook name will be different each time, but you would not confuse it with, say, the company budget workbook. So basically how do you want to identify the areas in the export workbook needing to be exported, and where exactly in the import workbook (the one that would host the code) would you want the export data to be imported.


Ha. You're right, it has. I suppose that is one of the benefits of the internet; advice offered can help many more indivuals than originally intended.

Luckily, the EXPORT workbook (which tends to have a similar name but not the same and is easily identifiable) always has sheets with the same names and the data that I need to copy is always in the same place in each respective sheet.
e.g. Productivity!B1:E10, Volumes Received!B1:E20 (not where the data actually tends to be, but you get the idea.

The IMPORT workbook has a sheet named Import Pimms which has set areas in which the data is pasted into. Because I know the sizes of the tables I'm pasting in, I've made sure there is adequate space for them.

I hope I've explained myself well enough to help you paint a mental image of what I'm after *crosses fingers*

Munni
 
Upvote 0
The copying and pasting part is relatively simple. The difficult part is telling Excel which workbook I want it to do the copying from.
 
Upvote 0
OK, assuming you want what's in...
Productivity!B1:E10 to be pasted into Import Pimms! upper left cell J5
and what's in...
Volumes Received!B1:E20 to be pasted into Import Pimms! upper left cell R5

then...
Please follow these directions exactly as I write them.

Step 1
Start by closing all workbooks in Excel except for the workbook that you want this functionality for, that is, your Import workbook that holds the Import Pimms worksheet.

Step 2
In this lone open workbook, from any worksheet press Alt+F11 to go into the Visual Basic Editor. Careful, that's ALT + F11.

Step 3
Hit Ctrl+R.

Step 4
In the Project - VBA Project window that is in the vertical pane on the left, find your workbook name in bold font. It will look like VBAProject (YourImportWorkbookName.xls)

Step 5
Expand the yellow Objects folder.

Step 6
Right click on the object named ThisWorkbook, and left click to select ViewCode.

Step 7
Paste this code into the large white window pane that is the workbook module:

Code:
Private Sub RightKlickMenuReeset()
On Error Resume Next
Application.CommandBars("wbNavigator").Delete
Err.Clear
End Sub
 
Private Sub RightKlickMenuMayker()
Dim objBar As Object, objBtn As Object, wb As Workbook
Run "RightKlickMenuReeset"
Set objBar = Application.CommandBars.Add("wbNavigator", msoBarPopup)
For Each wb In Workbooks
Set objBtn = objBar.Controls.Add
With objBtn
.Caption = IIf(wb.Name = ThisWorkbook.Name, wb.Name & " (this workbook)", wb.Name)
.Style = msoButtonCaption
.OnAction = "wbExport"
End With
Next wb
End Sub
 
Private Sub wbExport()
Dim strNameWB$, intAnswer%
strNameWB = Workbooks(Application.Caller(1)).Name
intAnswer = MsgBox("Import data from " & strNameWB & "?", 36, "Please confirm...")
If intAnswer = 7 Then
MsgBox "No problem, nothing will import.", 64, "You clicked No."
Exit Sub
End If
Application.ScreenUpdating = False
With Workbooks(strNameWB)
.Worksheets("Productivity").Range("B1:E10").Copy _
ThisWorkbook.Worksheets("Import Pimms").Range("J5")
.Worksheets("Volumes Received").Range("B1:E20").Copy _
ThisWorkbook.Worksheets("Import Pimms").Range("R5")
End With
Application.ScreenUpdating = True
MsgBox "Import complete.", 64, "Make time for beer."
End Sub

Step 8
While you are in the VBE, from the menu bar at the top, click Insert > Module, and paste this code into that new module:

Code:
Private Sub RightKlickMenuReeset()
On Error Resume Next
Application.CommandBars("wbNavigator").Delete
Err.Clear
End Sub
 
Private Sub RightKlickMenuMayker()
Dim objBar As Object, objBtn As Object, wb As Workbook
Run "RightKlickMenuReeset"
Set objBar = Application.CommandBars.Add("wbNavigator", msoBarPopup)
For Each wb In Workbooks
Set objBtn = objBar.Controls.Add
With objBtn
.Caption = IIf(wb.Name = ThisWorkbook.Name, wb.Name & " (this workbook)", wb.Name)
.Style = msoButtonCaption
.OnAction = "wbExport"
End With
Next wb
End Sub
 
Private Sub wbExport()
Dim strNameWB$, intAnswer%
strNameWB = Workbooks(Application.Caller(1)).Name
intAnswer = MsgBox("Import data from " & strNameWB & "?", 36, "Please confirm...")
If intAnswer = 7 Then
MsgBox "No problem, nothing will import.", 64, "You clicked No."
Exit Sub
End If
Application.ScreenUpdating = False
With Workbooks(strNameWB)
.Worksheets("Productivity").Range("B1:E10").Copy _
ThisWorkbook.Worksheets("Import Pimms").Range("J5")
.Worksheets("Volumes Received").Range("B1:E20").Copy _
ThisWorkbook.Worksheets("Import Pimms").Range("R5")
End With
Application.ScreenUpdating = True
MsgBox "Import complete.", 64, "Make time for beer."
End Sub

Step 9
Press Alt+Q.

Step 10
Save your workbook.

Step 11
Close your workbook.

Step 12
Open your workbook and any other workbooks, and when your workbook is activate, from any worksheet, you can right click a cell to see a pop up list of other open workbooks. Left click to select the workbook name you want to activate.

Note that the custom right click menu will only appear if more than one workbook is open in that same instance of Excel, and it will only appear in the subject workbook where the code is housed.
 
Upvote 0
I'm about to go home now as it is the end of a long day, but I will give your a solution a try tomorrow. Cheers for everything so far Tom.

Have an excellent rest of your day :)
 
Upvote 0
Thanks. So you know, I tested the code before I posted it so I know it works. If you get an error, be sure to look at the worksheet names you told me, exactly as you wrote them here as opposed to how they really are on the worksheet tab (a spacebar character here or there). Otherwise, you should be good to go.
 
Upvote 0
Hello Tom!

I did have the same goal as MunniMagic and i did follow your explanations and have copy the vba code in my workbook under ThisWorkbook and in the new module1, replaced the munnimagic sheet names by my sheet names and finally save and close excel.

Then launch excel again then load my worksheet (thisworksheet) plus the other worksheet with similar name but with always the same sheet names in it.

Now i activate ThisWorksheet by selecting it and do a Rightclick in any cell but i cannot see the expected list of other worksheet that i can select... Whats wrong?

Thanks :)
 
Upvote 0
I don't know what you mean by "ThisWorksheet". Sounds like something wasn't copied or pasted in the right place or the right way. Please take another look at what you did and if you are still stuck, email me your workbook so I can see what you are doing.
 
Upvote 0
This question came up earlier today. This macro would go into the first workbook, which allow you to find out the name of, and activate, the "other workbook".

Sub Test1()
Dim wb As Workbook, x As String
For Each wb In Workbooks
If wb.Name <> ThisWorkbook.Name Then x = wb.Name
Next wb
MsgBox "The other open workbook is named " & x & "." & vbCrLf & _
"Click OK to activate it."
Workbooks(x).Activate
End Sub


Tom,

I have a question I hope you can help me with. I am using Excel 2007 and am writing a macro that will copy the last worksheet from a file and copy as the last sheet in another file. The key factors are that the names for both files change each month as they include the month/year in the name. Also the last sheet in the source file is added daily to the file so the name is not constant either. I have gotten as for as being able to call up the source file using wildcards and select and copy the needed worksheet, but that is where everything derails. Your original code looked promising as I thought all I would have to do is change <> to = and I would be able to reference the destination file name that way. When I run the macro, I get Run-time Error 9: Subscript out of range with my bottom line highlighted.

Dim wb As Workbook, x As String


ChDir “C:\documents”
sfound = Dir(“C:\documents”
If sFound <> “” Then
Workbooks.Open “C:\documents” & “\” & sFound
End If
For Each wb In Workbooks
If wb.Name = ThisWorkbook.Name Then x = wb.Name
Next wb
Sheets(Sheets.Count).Copy After:=workbooks(x).Sheets(Sheets.Count)


I have also tried another variation but I get the same error in the same place.

Dim sFound As String
Dim cu As String

cu = ThisWorkbook.Name
ChDir “C:\documents”
sfound = Dir(“C:\documents”
If sFound <> “” Then
Workbooks.Open “C:\documents” & “\” & sFound
End If
Sheets(Sheets.Count).Copy After:=workbooks(x).Sheets(Sheets.Count)

Any help would be greatly appreciated.

Tom
 
Upvote 0

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