VBA to go to previous workbook

Akakumori

New Member
Joined
Jun 10, 2017
Messages
25
Hello,
I have little knowledge of VBA and I usually do my macros by recording and cleaning the code slightly.

I want to know if I am working with two different workbooks I can move between them with my macro without referring to their names because everytime I use the macro the names of the workbooks will be different. So each time macro won't work.

Thanks
 

Excel Facts

Lock one reference in a formula
Need 1 part of a formula to always point to the same range? use $ signs: $V$2:$Z$99 will always point to V2:Z99, even after copying
Before running the macro, make sure the workbook you want to set as wb1 is the active workbook.
Change the workbook refs in your code to wb1/wb2 instead the hard coded names.
Code:
Sub YourMacro()
Dim wb1 As Workbook, x$, wb2Name$, wb2 As Workbook
'Set active workbook as wb1
Set wb1 = ActiveWorkbook
'Identify wb2
x = Application.GetOpenFilename
'Get name of selected file
wb2Name = Right(x, Len(x) - InStrRev(x, "\"))
'Check if selected file is open and, if not, open it
If Not bFileOpen(wb2Name) Then Workbooks.Open (x)
'Set selected file as wb2
Set wb2 = Workbooks(wb2Name)
'For testing - delete these 2 lines later
MsgBox "wb1 is :  " & wb1.Name
MsgBox "wb2 is :  " & wb2.Name


'Your code here :


End Sub


Function bFileOpen(wbname As String) As Boolean
On Error Resume Next
bFileOpen = Len(Workbooks(wbname).Name)
On Error GoTo 0
End Function
 
Upvote 0
Hi footoo,
Thanks so much for your reply.
Not so sure how I should be replacing the workbooks refs in my code to wb1/wb2. If I have one function which is opening my workbook from certain location. Should I just change the name of the workbook itself?

Thanks
 
Upvote 0

Forum statistics

Threads
1,223,882
Messages
6,175,165
Members
452,615
Latest member
bogeys2birdies

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