Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

VBA changing active workbook

Tags:

excel

vba

I have a spreadsheet where in the VBA it goes off opening other spreadsheets and temporarily setting these to the active worksheet.

However, I have a loop and at the end of the first iteration I need to set the active worksheet to be the original one which started the VBA module. I cannot set a new Workbook object to open the original, because the original is still open in the background and it says its already open.

My problem is that I need to change the active Workbook to the original one, when I never had a workbook object to refer to it???

'Original workbook is active implicitly

'loop begins

'change active workbook to something else


'Need to change back to original workbook here- but don't have a VBA workbook object

'end of loop
like image 666
mezamorphic Avatar asked Sep 12 '12 10:09

mezamorphic


People also ask

How do I change the active workbook name in VBA?

To RENAME an Excel file that is stored on your computer, you need to use the “NAME” statement. In this statement, you need to define the old file name and the new name that you want to apply. But there's one thing that you need to remember the file must be closed.

Which workbook is active VBA?

The ActiveWorkbook is the workbook that you (or the user) has selected before running the macro. The ActiveSheet is the worksheet tab that is currently selected before running the macro. If multiple sheets are selected, the ActiveSheet is the sheet that is currently being viewed.


1 Answers

Use ThisWorkbook which will refer to the original workbook which holds the code.

Alternatively at code start

Dim Wb As Workbook
Set Wb = ActiveWorkbook

sample code that activates all open books before returning to ThisWorkbook

Sub Test()
Dim Wb As Workbook
Dim Wb2 As Workbook
Set Wb = ThisWorkbook
For Each Wb2 In Application.Workbooks
    Wb2.Activate
Next
Wb.Activate
End Sub
like image 160
brettdj Avatar answered Nov 15 '22 09:11

brettdj