What event happens when I select a sheet? - vba

What I am trying to accomplish is fairly simple. When a user selects a sheet, I would like a message box to appear. Meaning: I'm currently viewing Sheet1, I click on the Sheet2 tab and a message pops up before I can do anything. I can't seem to find the event that fires when moving to a different sheet.
Events I've tried: Workbook_SheetActivate and Worksheet_Activate
Private Sub Workbook_SheetActivate(ByVal sh As Object)
MsgBox ("Example Message")
End Sub
Or
Private Sub Worksheet_Activate()
MsgBox ("Example Message")
End Sub
I've done some googling and most things are about when cell values change or the cell selection changes.

This should work:
Private Sub Worksheet_Activate()
MsgBox "you never visit...you never call....you never write"
End Sub
However:
code must be in the worksheet code area
macros must be enabled
events must be enabled

You could use the following in the "ThisWorkbook" module to fire a message whenever you change sheets within the workbook.
Sub Workbook_SheetActivate(ByVal Sh As Object)
MsgBox Sh.Name & " activated!"
End Sub
This will solve the problem without having to add Private Sub Worksheet_Activate() to every worksheet's code module.

Here is a link to all the worksheet events available in Excel:
http://dmcritchie.mvps.org/excel/event.htm
Private Sub Worksheet_Activate()
Private Sub Worksheet_BeforeDoubleClick(ByVal Target As Range, Cancel As Boolean) -- (additional examples)
Cancel = True 'turn off Edit mode when using “Edit directly in a cell”
Private Sub Worksheet_BeforeRightClick(ByVal Target As Range, Cancel As Boolean)
Cancel = True 'turn off Edit mode when using “Edit directly in a cell”
Private Sub Worksheet_Calculate()
Private Sub Worksheet_Change(ByVal Target As Range)
Application.EnableEvents = False 'should be part of Change macro
Application.EnableEvents = True 'should be part of Change macro
Private Sub Worksheet_Deactivate()
Private Sub Worksheet_FollowHyperlink(ByVal Target As Hyperlink)
Private Sub Worksheet_SelectionChange(ByVal Target As Range)
Doesn't Worksheet_Activate work for you?

You need to have the event in the worksheet that is being activated - that is, if you put it is sheet 2, it will fire only when that sheet is opened.
This worked in sheet 2 of my workbook.
Sub worksheet_activate()
MsgBox "activated!"
End Sub

Related

Limiting user interaction with the workbook - hide workbook / show only userform

Is it possible to get the same effect using ThisWorkbook.Application.Visible = False but only for one Workbook. I mean, I'd like to limiting user interaction only to UserForm, but I need have an access to anothers workbooks. At the moment this function cause hide workbook, but after open some another excel file - all object from userform are not available.
Private Sub Workbook_Open()
ThisWorkbook.Application.Visible = False
Starter.Show modeless
End Sub
Thanks for your support.
Please, create a form, let us say "Starter", having (at least) a button ("btExit"), copy the next code in its code module and show it. If the form in discussion already has some code in Initialize and Terminate events, please add the next code lines, too:
Option Explicit
Private Sub btExit_Click()
Unload Me
End Sub
Private Sub UserForm_Initialize()
ThisWorkbook.Windows(1).Visible = False
End Sub
Private Sub UserForm_Terminate()
ThisWorkbook.Windows(1).Visible = True
End Sub
So, you can simple use workbook Open event in this way:
Private Sub Workbook_Open()
Starter.Show vbModeless
End Sub

Remember cell selected before double click

I have an Excel sheet that has a doubleclick event in cell "P1" (runs a macro).
I may have cell "J30" (or any other cell) selected before I doubleclick "P1"
How can I remember, and return to the cell "J30" after the "P1" doubleclick?
Storing the active cell doesn't work because the first click in the doubleclick sequence, selects "P1".
I also tried rightclick on "P1", but it also selects "P1" before running the event.
Well, it's a bit more complicated than the "duplicate thread" because the SelectionChange event is invoked prior to the BeforeDoubleClick event, so the former will update the last selection to the new one before the latter gets hand.
What you need is to go "one step further" in saving the selections, by actually saving both:
The current selection
The previous selection
Something like this should work
' Code module of your worksheet
Option Explicit
Private lastSelection As Range, beforeLastSelection As Range
Private Sub Worksheet_BeforeDoubleClick(ByVal Target As Range, Cancel As Boolean)
' Your Code for this event, i.e.
If Target.Address = "$P$1" Then
' Some code ...
Cancel = True
If Not beforeLastSelection Is Nothing Then beforeLastSelection.Select
End If
End Sub
Private Sub Worksheet_SelectionChange(ByVal Target As Range)
Set beforeLastSelection = lastSelection
Set lastSelection = Target
End Sub
Using the method here you can do as follows
Public PreviousActiveCell As Range
Private Sub Worksheet_BeforeDoubleClick(ByVal Target As Range, Cancel As Boolean)
MsgBox ("Previous selection: " & PreviousActiveCell.Value & vbNewLine & _
"Double clicked selection: " & Target.Value)
End Sub
Private Sub Worksheet_SelectionChange(ByVal Target As Range)
Static pPrevious As Range
Set PreviousActiveCell = pPrevious
Set pPrevious = ActiveCell
End Sub

Re-using a VBA macro with "Worksheet_Change" event in all open workbooks in a single file

The following VBA code snippet should be executed in all open workbooks within a single Excel file (*.xlsm):
Private Sub Worksheet_Change(ByVal Target As Range)
...
End Sub
We do not want to copy the code in each workbook to reduce code duplication.
When trying to create a new Macro via the Excel "Macro" dialog it offers the possibility to locate the Macro in:
all open workbooks
this/current workbook
current file
When choosing (1) in combination with a Macro name, e.g. "MultiSelect" Excel jumps in the VBA editor and scaffolds a basic method according to the given name:
Sub MultiSelect()
...
End Sub
Our question: how to guarantee reacting on "Worksheet_Change" events within this macro?
With the help of "Robin Mackenzie" I found a solution :) Especially, reading section Application Events In A New Class Module helped. So, I created a new class named "CExcelEvents":
Private WithEvents App As Application
Private Sub App_SheetChange(ByVal Sh As Object, ByVal Target As Range)
'gets the code more robust when the SheetChange event is called twice
If Me.EnableEvents = False Then
Exit Sub
End If
Application.EnableEvents = False
...//code to centralize
Application.EnableEvents = True
Me.EnableEvents = False
End Sub
Private Sub Class_Initialize()
'setting a variable for this object
Me.EnableEvents = True
Set App = Application
End Sub
and added in each worksheet - where the central code located in CExcelEvents has to be executed - the following object creation scaffold:
Private XLApp As CExcelEvents
Private Sub Worksheet_Change(ByVal Target As Range)
Application.EnableEvents = False
Set XLApp = New CExcelEvents
Application.EnableEvents = True
End Sub
To prevent eventloops, see: Run a macro when certain cells change in Excel but from my Personal workbook

Getting this code to work for all sheets in a workbook?

I need this code to work for all sheets:
Private Sub Worksheet_SelectionChange(ByVal Target As Excel.Range)
Application.ScreenUpdating = True
End Sub
Right now I've been adding it to every sheet one by one, but how do I just add it to the workbook so every sheet has it?
Private Sub Workbook_SheetSelectionChange(ByVal Sh As Object, ByVal Target As Range)
Application.ScreenUpdating = True
End Sub
This worked for me. What I had to do was change my object to include the workbook itself. I clicked on the dropdown to see my available options which is where I found the one I needed.
Bad: Worksheet_SelectionChange
Good: Workbook_SheetSelectionChange

Excel Userform with Textbox, how to toggle through values in range of textbox

Purpose: Click on a cell in a range (Range: Column K:K on excel worksheet). Once you click on a specific cell in column K, userform pops up with cell value using following code:
Private Sub Worksheet_SelectionChange(ByVal Target As Range)
On Error Resume Next
If Target.Cells.Count > 1 Then Exit Sub
If Not Intersect(Target, Range("K:K")) Is Nothing Then
Credit_Information.TextBox1.Value = Target.Value
Credit_Information.Show
End If
End Sub
My question, is depending on where I click on column K, I want to use two buttons on my userform (Previous and Next) to move up and down column K and see the values of the cell dynamically change on my userform. Is this possible? Please let me know if any clarification is needed.
Just add the two command buttons to your userform.
Name one of the buttons cmdNext and give it a caption of "Next".
Name the other button cmdPrev and give it a caption of "Previous".
Then, in the userform code module, place these routines:
Private Sub cmdNext_Click()
ActiveCell(2).Select
End Sub
Private Sub cmdPrev_Click()
If ActiveCell.Row > 1 Then ActiveCell(0).Select
End Sub
That's it.
Note: if you want you can add code to ensure that the ActiveCell is in column K before allowing the new selections:
If ActiveCell.Column = 11 Then ...
Perfect, Thanks!
I also found out that using Offset worked for me too in this manner. I'm not sure however if I'm breaking any conventions by doing this.
Private Sub CommandButton1_Click()
ActiveCell.Offset(-1).Activate
End Sub
Private Sub CommandButton2_Click()
ActiveCell.Offset(1).Activate
End Sub
It is possible, but I would create another procedure for that. What you could do is declare a public variable in your userform & set it equal to the range Target. Then you could call another procedure from the userform on each button click and redefine the selected range after each click.
So, at the top of your userform do this:
Public selected_cell as Range
Then for the up button:
Private Sub ButtonUp.Click()
If selected_cell.Row < 2 Then Exit Sub
selected_cell.Rows(0).Select
Set selected_cell = selected_cell.Rows(0)
me.TextBox1.Value = selected_cell
End Sub
And the down button would be:
Private Sub ButtonDown.Click()
selected_cell.Rows(2).Select
Set selected_cell = selected_cell.Rows(2)
me.TextBox1.Value = selected_cell
End Sub
Now let's make your code like this:
Private Sub Worksheet_SelectionChange(ByVal Target As Range)
On Error Resume Next
If Target.Cells.Count > 1 Then Exit Sub
If Not Intersect(Target, Range("K:K")) Is Nothing Then
With Credit_Information
Set .selected_cell = target
.TextBox1.Value = Target.Value
.Show
End With
End If
End Sub