Reopen workbook at last active sheet - excel

How can I reopen my workbook at the last active sheet when I click on a hyperlink that runs ForceReopen? What I have fails because LstSht is not set. (Note that I do not want to save changes when I run ForceReopen.)
' Workbook module
Private Sub Workbook_SheetDeactivate(ByVal Sh As Object)
Set LstSht = Sh
End Sub
' Standard module
Public LstSht As Worksheet
Sub ForceReopen()
Application.OnTime Now + TimeValue("00:00:01"), "GoToLast"
ThisWorkbook.Close False
End Sub
Sub GoToLast()
LstSht.Activate
End Sub

You need to store the name of the last active sheet somwhere. Since you don't want to save the file on close, it can't be in the file itself.
One possibility is to create a small text file that contains just the sheet name to activate on file open. The workbook open event can then read the text file and activate the specified sheet.
The workbook activate event should update the text file. Provide error handlers to allow for the text file not existing, or the specified sheet not existing. Depending on how robust you want to make it, you might need to handle the sheet name changing too.
Location of the text file is a design choice: maybe the same folder as the Excel file, or some fixed config folder.
Another possibility would be to use the registry rather than a text file.

Remember something during automatic reopen within Application.Caption
You may store the ActiveSheet.Name within Application.Caption during a forced reopening of a workbook, even if all other global variables are lost.
' Within ThisWorkbook:
Private Sub Workbook_BeforeClose(Cancel As Boolean)
Application.Caption = "Last Active: " & ActiveSheet.Name
' Stop ' temporary to see the caption, but restart will not work!
End Sub
' Both following subs within a normal module:
Public Sub ForceReopen()
Application.OnTime Now + TimeValue("00:00:01"), "GoToLast"
ThisWorkbook.Close False
End Sub
Private Sub GoToLast()
Dim iLastSheet As Integer ' Position of text "Last Active" in Caption
iLastSheet = InStr(Application.Caption, "Last Active:")
' Stop ' temporary to see "Last Active: ..." in the caption
If iLastSheet > 0 Then
On Error Resume Next
ThisWorkbook.Sheets(Mid(Application.Caption, iLastSheet + 13)).Activate
On Error GoTo 0
Application.Caption = ""
End If
End Sub
If you save the workbook staying in Sheet1 and start ForceReopen staying in Sheet3 (by button, by hyperlink, by manual execution, whatever) then it reopens at Sheet3.
To check the functionality, you may add the first Stop to see, if Application.Caption is set correctly (workbook will not open afterwards, so you have to delete this Stop after testing):
You may add the second Stop to check, if Application.Caption is set as intended after it reopened automatically:

There is a logical flaw in your plan. Why should you activate the last viewed sheet and then close the workbook without saving that change?
Set a public variable by the name of LstSht. (I would prefer it to be the sheet name rather than the sheet object but that may be a matter of taste.
Set the variable on the Activate event of each sheet. Note that the Activate event may not occur when you first open the workbook. Therefore the variable must also be set in the Workbook_Open event.
In the GoToLast procedure provide for the eventuality that the variable doesn't hold a value - just in case. Use On Error Resume Next. Also make sure that the sheet isn't activated if it is already active. You may make this procedure a function and let it return True if the sheet was changed (for whatever purpose).
The effect of the whole thing, as you have laid it out, would be that, in the middle of whatever you are doing, the last active sheet is suddenly activated and then the workbook closed without saving your work. Charming idea!

Related

How to have excel wait for a workbook to open

My application currently navigates to a vendor website, logs in, opens a report, clicks a download button behind an IFrame(which was cancer to get working), and hits the open button on the open/save dialog box. Now all thats left for this phase of the project is to have excel wait for the new workbook to open, pull the information into a new sheet, and close the other workbook.
The problem is that no matter what I seem to try the new workbook will never open while the macro is running. If i add a break in the code everything works just fine. I've tried application.wait, sleep, DoEvents, and even a msgbox. I'm kinda stumped here.
'This clicks the button that initiates the open/save dialog box in IE
iWin.contentDocument.querySelector("a[title=Excel][onclick*=EXCELOPENXML]").Click
'set the name of the windows the program should look for
iStr = "Reports LeaveXpert Application - Internet Explorer"
eStr = "Case Detail.xlsx [Protected View] - Excel"
'these are declared as longptr
leHwin = 0
cdHwin = 0
'Grabs the windows handle for the IE window
leHwin = FindWindow(vbNullString, iStr)
'Makes sure the IE window is active
i = SetForegroundWindow(leHwin)
'a little bit of delay
Application.Wait DateAdd("s", 5, Now)
'Send the key combination for the open button to the open browser
Application.SendKeys "%{O}"
cdHwin = 0
Debug.Print cdHwin
'this should wait for the new spreadsheet to open but instead the application hangs here and the new spreadsheet never opens.
Do While cdHwin = 0
'various methods of having the program wait that i've tried
'DoEvents
'Application.Wait (Now() + TimeValue("00:00:01"))
'Sleep 1000
'this should set the variable to the windows handle of the new sheet once it opens causing the loop to stop
cdHwin = FindWindow(vbNullString, eStr)
'This just keeps giving me 0 as an output
Debug.Print cdHwin
Loop
'we never get to this line of code unless I add a break somewhere in the loop, then the sheet opens and I get the windows handle as output.
Debug.Print cdHwin
UPDATE:
IT FINALLY WORKS!!!!!!!!!!!!!!!
I'll have to rethink my single button approach to implementation, but that's a pretty small price to pay. This has been an off and on project for the better part of 2 weeks and has taken me far more time than I anticipated, mostly due to IFrames being absolute cancer (I seriously hate them). But I've learned a lot getting this first part working. Now to start on getting the other two relevant data sources integrated into the spreadsheet. The more I learn about computer programming; the more I realize how little I know about it.
Oh and Mathieu-Guindon is an absolute hero!
UPDATE 2 for posterity.
Nothing to see here. I thought I had resolved the problem, but as it turns out I just need more sleep. Relevant quote from comment discussion.
"I really need to stop staying up till 4 AM reading posts about computer code and trying to work on this thing. I really think that I went to sleep, had a dream about fixing it, woke up and posted about the "fix", and thought it was real."
Update 3: Final Update on this question. Relevant explanation is in the comments on the following code.
'I made 2 changes that seem to have resolved the issue.
Private Sub AppEvents_WorkbookOpen(ByVal Wb As Workbook)
If Left(Wb.Name, 11) = CaseDetailFileName Then
'This sub that handles the transfer of data from the newly opened workbook to this workbook.
'It had an internal call to close the newly opened workbook that I forgot about, so I removed it
ImportCase Wb
'a duplicate call also existed out here, there were also a few duplicate ".activate"
'commands inside the import sub and this if statement that I removed
Wb.Close
'This sub handles data sorting and analytics
CaseFAS
End If
'I had tried copying this line from Workbook_Open a few times before and it
'didn't resolve the issue by itself,
'but I'm reasonably sure it is part of the solution
Set AppEvents = Me.Application
End Sub
A peek under the hood of ImportCase for completeness sake.
'This sub handles importing the optis workbook when it opens. It's called by
'the AppEvents_WorkbookOpen sub declared in ThisWorkbook
Public Sub ImportCase(ByVal book As Workbook)
Dim srcSht As Worksheet
Set srcSht = ThisWorkbook.Sheets("OptisSource")
'This line clears out any old data
srcSht.Cells.Clear
'Sets the newly opened workbook to be the active sheet
book.Sheets("Case Detail").Activate
'Copys the information and sends it to a predefined sheet in this workbook
ActiveSheet.UsedRange.Copy Destination:=srcSht.Range("A1")
'sets the newly imported information to the active sheet
srcSht.Activate
'This sub clears out ghost data
ClearNulls
End Sub
What if we just let Excel do its thing, and go with the flow of an event-driven / desynchronized paradigm?
The Excel.Application class raises a number of events you can handle in any class module, but the ThisWorkbook module can do - you declare a WithEvents module-level variable:
Option Explicit
Private WithEvents AppEvents As Excel.Application
And then you initialize it with an Application object reference, perhaps on open - if we're in the ThisWorkbook module, we're inheriting an Application property from the base Excel.Workbook class:
Option Explicit
Private WithEvents AppEvents As Excel.Application
Private Sub Workbook_Open()
Set AppEvents = Me.Application
End Sub
Declaring a WithEvents variable makes it available in the top-left dropdown, and then we can pick a member to implement with the top-right dropdown:
One of the events we can handle at the Application level, is a rather convenient WorkbookOpen event that gives us a Wb As Workbook reference to the workbook that was just opened:
Private Sub AppEvents_WorkbookOpen(ByVal Wb As Workbook)
End Sub
Here you get to intercept every workbook that opens during a macro-enabled session, as long as this AppEvents reference remains in-scope - that is, until ThisWorkbook is closed.
So the ThisWorkbook might look like this:
Option Explicit
Private Const CaseDetailFileName As String = "Case Detail.xlsx"
Private WithEvents AppEvents As Excel.Application
Private Sub Workbook_Open()
Set AppEvents = Me.Application
End Sub
Private Sub AppEvents_WorkbookOpen(ByVal Wb As Workbook)
If Wb.Name = CaseDetailFileName Then
DoThingWithCaseDetailWorkbook Wb
End If
End Sub
And then Public Sub DoThingWithCaseDetailWorkbook(ByVal book As Workbook) could be defined in any standard module and have access to any module state/variable that was set before the WorkbookOpen event fired.
Now the fact that the file is being opened in protected mode (from an untrusted location?) might interfere with this, but then there should be a way to get the script to save the file elsewhere if it's a problem.

VBA: About go back to target(sheet change event) cell or at least that target sheet after below procedures

I am a beginner of VBA :D I am creating LogSheet to record any changes from sheets. From beginning I want to check if the 'LogSheet' exists already when sheetchange event fired. So I put this 'check procedures' at beginning of SheetChange event. But the annoying thing is if 'Logsheet' not existing then It creats one and the active sheet switch to that new created 'LogSheet'.
My question is if there could be a method: after change event fired and new LogSheet created, the selection will go back to the target that I just changed before, rather than stay in 'LogSheet'.
enter image description here
edited to add more about Me keyword
to activate your "calling" sheet just use
Me.Activate
since in any code in a sheet code pane the keyword Me refers to the sheet itself
but you could also benefit from a "helper" function (explanation in comments):
Function CreateSheet(shtName As String, sht As Worksheet) As Boolean
On Error Resume Next'prevent possible next statement error to stop code execution
Set sht = Worksheets(shtName)' try setting the sheet with passed name
On Error GoTo 0' restore default error handling
If sht Is Nothing Then' if there was not such sheet with passed name
Set sht = Worksheets.Add(after:=Sheets(Sheets.Count))' set a new one
sht.Name = shtName' give new sheet the passed name
Me.Activate' activate back the "calling" sheet
CreateSheet = True'return 'True' and have calling sub know that a new sheet hase been created and passed back via 'sht' parameter
End If
End Function
this function must reside
not to clutter your Change event sub, as follows:
Private Sub Worksheet_Change(ByVal Target As Range)
Dim logSht As Worksheet
If CreateSheet("Logsheet", logSht) Then
logSht.Range("A1:O1").Value = Array(...)
MsgBox "Log Sheet has been created ..."
Else
MsgBox "Log Sheet has already been created BEFORE..."
End If
End Sub

How to make Application.key Shortcuts WorkBook Specific?

I added code to a series of similar files for different projects.
I defined a (Control + R) "^ + R" shortcut to let users see the current record in a userform.
I added application.key code on workbook activating and deactivating event, so the shortcut can be used when several files of this type are open.
My problem is even if the form opens and reads the data from the respective workbook, the userform is not called from the respective file!
Should I localize the procedure as well?
Here are my codes:
The Code in ThisWorkbook
Private Sub Workbook_Activate()
With Application
.OnKey "^R", "ReadCurrentRecord"
End With
End Sub
Private Sub Workbook_Deactivate()
Application.OnKey "^R"
End Sub
The Code in a general Module
Sub ReadCurrentRecord()
If ActiveCell.Worksheet.Name = "OSW" Then
If OSWRng Is Nothing Then
Set OSW = ThisWorkbook.Sheets("OSW")
Set OSWRng = OSW.Range("a5:bz2000")
End If
FrmWODetails.Tag = OSW.Cells(ActiveCell.Row, 14)
FrmWODetails.UserForm_Activate
FrmWODetails.Show vbModeless
End If
End Sub
All the Names are same in the files.
thisworkbook and activecell may not be what you expect them to be.
if this is an addin, this workbook will refer to the addin while active cell wont. i don't even know if activate a cell can be used in an add-in' sheet... I'm thinking not, I'll test that then i get to s computer for my own knowledge.
it's almost always best to fully qualify the object, sometimes from the application level but normally the workbook will suffice
personally, I prefer codenames over names and babes over indexes but they have a few drawbacks that keep them from being my#1 choice

Excel VBA: Workbook_Open

I'm using Workbook_Open to call a userform when the application is opened, this is working fine. However I would like it to only run the first time it is opened.
I tried this and it work if I run the sub from the editor but not when I open the file.
Sub Workbook_Open()
If Worksheets("DataSheet").Range("A1").Value = "" Then
QuickStartForum.Show
End If
End Sub
Note: A1 contains a value that will be populated after the user form has run
It appears that the problem is that it opens the user form before the data is loaded into the worksheet.
Is this there a way around this or do I need to take a different approach ?
I think it is because you have this code in a Module. You need to put the code within 'ThisWorkBook'.
I tried this following code and had no issues when it was in the 'ThisWorkBook' it failed to run within 'Module1'
Private Sub Workbook_Open()
If Worksheets("DataSheet").Range("A1").Value = "" Then
QuickStartForum.Show
Worksheets("DataSheet").Range("A1").Value = "filled" ' <-- this fills the cell with data for testing, so that when you reopen the file it should not re-open the userform
Else
MsgBox ("not shown because the A1 cell has data")
End If
End Sub

Automatically sum of new added Excel Sheet in Total Sheet

I have an Excel workbook in which I have tabs representing dates along with sum in each tab. Although I can take the sum of all these in the final sheet, I want a formula/macro to get the sum in the total named sheet, when a new spreadsheet is being added.
Note:- the cell in all would remain the same (E56)
I do not understand what you are attempting. Until the user has placed information in the new sheet that results in a value in E56, I see little point to adding the value of NewSheet!E56 to the total sheet.
However I suspect you need to use events. Below are a number of event routines which must be placed in the Microsoft Excel Object ThisWorkbook for the workbook. These just output to the Immediate window so you can see when they are fired. Note: several can be fired for one user event. For example, creating a new worksheet, triggers: "Create for new sheet", "Deactivate for old sheet" and "Activate for new sheet".
Do not forget to include
Application.EnableEvents = False
Application.EnableEvents = True
around any statement within one of these routine that will trigger an event.
Perhaps you need to use SheetDeactivate. When the users leaves a sheet, check for a value in E56. If present, check for its inclusion in the totals sheet. Have a play. Do what your users do. Add to these routines to investigate further. Good luck.
Private Sub Workbook_SheetActivate(ByVal Sh As Object)
Debug.Print "Workbook_SheetActivate " & Sh.Name
End Sub
Private Sub Workbook_BeforeClose(Cancel As Boolean)
Call MsgBox("Workbook_BeforeClose", vbOKOnly)
End Sub
Private Sub Workbook_SheetChange(ByVal Sh As Object, ByVal Source As Range)
Debug.Print "Workbook_SheetChange " & Sh.Name & " " & Source.Address
End Sub
Private Sub Workbook_SheetDeactivate(ByVal Sh As Object)
Debug.Print "Workbook_SheetDeactivate " & Sh.Name
End Sub
Private Sub Workbook_NewSheet(ByVal Sh As Object)
Debug.Print "Workbook_NewSheet " & Sh.Name
End Sub
Sub Workbook_Open()
Debug.Print "Workbook_Open"
End Sub
Extra section in response to clarification of requirement
The code below recalculates the grand total of cell E56 for all worksheets except TOTAL and stores the result in worksheet TOTAL every time the workbook is opened and every time the user changes the current worksheet.
It is difficult to get consistent timings with Excel but according to my experimentation you would need between 500 and 1,000 worksheets before the user would notice a delay switching worksheets because of this recalculation.
I am not sure if you know how to install this code so here are brief instructions. Ask if they are too brief.
Open the relevant workbook.
Click Alt+F11. The VBA editor displays. Down the left you should see the Project Explorer. Click Ctrl+R if you do not. The Project Explorer display will look something like:
.
VBAProject (Xxxxxxxx.xls)
Microsoft Excel Objects
Sheet1 (Xxxxxxxxx)
Sheet10 (Xxxxxxxxx)
Sheet11 (Xxxxxxx)
:
ThisWorkbook
Click ThisWorkbook. The top right of the screen with turn white.
Copy the code below into that white area.
No further action is required. The macros Workbook_Open() and Workbook_SheetDeactivate() execute automatically when appropriate.
Good luck.
Option Explicit
Sub CalcAndSaveGrandTotal()
Dim InxWksht As Long
Dim TotalGrand As Double
TotalGrand = 0#
For InxWksht = 1 To Worksheets.Count
If Not UCase(Worksheets(InxWksht).Name) = "TOTAL" Then
' This worksheet is not the totals worksheet
If IsNumeric(Worksheets(InxWksht).Range("E56").Value) Then '###
TotalGrand = TotalGrand + Worksheets(InxWksht).Range("E56").Value
End If '###
End If
Next
'Write grand total to worksheet TOTAL
' ##### Change the address of the destination cell as required
Worksheets("TOTAL").Range("D6").Value = TotalGrand
End Sub
Sub Workbook_Open()
' The workbook has just been opened.
Call CalcAndSaveGrandTotal
End Sub
Private Sub Workbook_SheetDeactivate(ByVal Sh As Object)
' The user has selected a new worksheet or has created a new worksheet.
Call CalcAndSaveGrandTotal
End Sub
I know this is the programming forum, but this particular "need" seems to be solvable without all the plumbing.
I like the old hidden FIRST and LAST sheets trick.
Create a sheet called First
Create a sheet called Last
Place your current data sheets between these two sheets.
Hide the sheets First and Last
Now you can use 3D formulas to sum cells from all these sheets, like so:
=SUM(First:Last!E56)
Now just add sheets to your workbook AFTER the last visible data sheet and Excel will still slip it in ahead of the hidden LAST sheet, so your formula just expands itself that way

Resources