PDA

View Full Version : activate original window at end of macro?



urungus
10-14-2007, 09:17 AM
Hi, I'm a beginning VBA programmer.

I'm writing an Excel Macro that opens a second workbook, and makes a few alterations to it.

At the end of the Macro, I'd like to re-activate the original workbook and sheet that were active when the Macro started.

I recorded a Macro and it gave me this code to reactivate the original sheet:

Windows("mySpreadsheet.xls").Activate
Sheets("Sheet2").Select

I'd like to make it more general, so the code won't break if the name of the original is changed from "mySpreadsheet.xls"

something like

Dim NameOfOriginalWindow As String
Dim NameOfOriginalSheet As String
NameOfOriginalWindow = ??????????????
NameOfOriginalSheet = ??????????????
...
[main body of code]
...
Windows(NameOfOriginalWindow).Activate
Sheets(NameOfOriginalSheet).Select


Thanks for any help.

Norie
10-14-2007, 10:30 AM
urungus

The easiest way to deal with this would be to not activate anything in the first place.

Selecting/activating just isn't needed except in some special cases.

mdmackillop
10-14-2007, 11:17 AM
Sub Resets()
Dim WBOrig As Workbook, SHOrig As Worksheet
Set WBOrig = ActiveWorkbook
Set SHOrig = ActiveSheet

'Do your stuff


WBOrig.Activate
SHOrig.Activate
End Sub

Cyberdude
10-14-2007, 11:35 AM
Hey, urungus, welcome to VBAX!

There are probably any number of variations of the following, but (with apologies to Norie), you might try something like this:

Dim WkBkNmSave As String
WkBkNmSave = ThisWorkbook.Name
. . .
Workbooks.Open Filename:="C:\Excel Documents\ABC.xls"
?Run a macro that belongs to workbook ?ABC?
Application.Run "'ABC.xls'!MacroNm"
'Reactivate this workbook
Workbooks(WkBkNmSave).Activate

?OR forget saving the original workbook name
? and use the following statement instead:
Workbooks(ThisWkBkNm).Activate

Norie
10-14-2007, 12:50 PM
Cyberdude

No need for apologies.:)

That code should work but I really think the best route would be to avoid the activating/selecting in the first place.

I've not posted any code because the OP hasn't actually the code that is meant for the opened workbook.

Hard to illustrate how select/activate isn't needed without that.:bug: