Excel vba: detect worksheet switch: when another worksheet gets selected - excel

Suppose I have a workbook with two worksheets: Sheet1 and Sheet2. I want a message to appear when a user goes from Sheet2 back to Sheet1.
I'm not sure how to approach it - so far I've only been meddling with Worksheet_Change sub, but the problem doesn't seem like something that could be solved inside that sub. Right now, I can only think of setting some global variable
Dim previousWorksheet As Variant
Set previousWorksheet = ActiveSheet.Name
And then checking what sheet is the active one:
If previousWorksheet = "Sheet2" And ActiveSheet.Name = "Sheet1" Then
MsgBox("DETECTED")
End If
But what would trigger that code, I don't know.
What is the best way to accomplish it?

This is what worked for me (inside ThisWorkbook module):
Option Explicit
Dim previousWorksheet As String
Private Sub Workbook_open()
previousWorksheet = ActiveSheet.Name
End Sub
Private Sub Workbook_SheetActivate(ByVal Sh As Object)
MsgBox ("changed")
If ActiveSheet.Name = "Sheet1" And previousWorksheet = "Sheet2" Then
MsgBox ("the switch")
End If
previousWorksheet = ActiveSheet.Name
End Sub

Suppose I have a workbook with two worksheets: Sheet1 and Sheet2
then to get a message
when a user goes from Sheet2 back to Sheet1
you could simply go:
Private Sub Workbook_SheetActivate(ByVal Sh As Object)
If Sh.Name = "Sheet1" Then MsgBox "The switch"
End Sub

Related

How do I amend this VBA so it runs when a specific worksheet is selected?

I have this VBA written. Essentially what it does is; I've used 'Define Range' ("Test") on a few cells in a worksheet. The VBA makes sure that whenever the workbook is opened, it automatically zooms in to fit that range. Right now, I think it only triggers when the workbook is opened, and it gives an error message if that worksheet is not selected when the workbook is opened. Now, I would like it to run only if the specific worksheet is selected. I've literally copied it from someone else so don't really know how I would amend this...
Thanks in advance!
Private Sub Workbook_Open()
Range("Test").Select
ActiveWindow.Zoom = True
Cells(1, 1).Select
End Sub
Zoom & Scroll To Cell When Worksheet Is Activated...
... and if the worksheet is active when the workbook is opened.
It is assumed that the range is of Workbook scope.
ThisWorkbook Module
Option Explicit
Private Sub Workbook_Open()
Const WorksheetName As String = "Sheet1"
If ActiveSheet.Name = WorksheetName Then SelectMyRange
End Sub
Sheet Module, e.g. Sheet1...
... where Sheet1 is the code name i.e. the name not in parentheses, e.g. Sheet1(Data), seen in the VBE Project Explorer window.
Option Explicit
Private Sub Worksheet_Activate()
SelectMyRange
End Sub
Standard Module, e.g. Module1...
... created by using Insert Module.
Option Explicit
Sub SelectMyRange()
Const RangeName As String = "Test"
With Range(RangeName)
.Select
ActiveWindow.Zoom = True
Application.Goto .Cells(1), True
End With
End Sub

Trying to create a excel worksheet using data from a VBA form then adding it to end of workbook

Trying to create a excel worksheet using data from a VBA form then adding it to end of workbook. Please help to activate the code
Private Sub Add_Tab_Click()
Dim txtNameSur As Worksheet
Set txtNameSur = Worksheets("Me.Textbox1")
ThisWorkbook.Sheets(1).Copy after:=Sheets(Sheets.Count)
Newname = Worksheets.Add.Name = Userform1.txtNameSur.Value
ActiveSheet.Name = Newname
End Sub
The goal in your question is a bit unclear, but I guess you meant to do something like below:
Private Sub Add_Tab_Click()
'copy first worksheet to the end of the workbook
ThisWorkbook.Worksheets(1).Copy After:=ThisWorkbook.Sheets(ThisWorkbook.Sheets.Count)
'set the copied worksheet to a variable `NewWorksheet`
Dim NewWorksheet As Worksheet
Set NewWorksheet = ThisWorkbook.Sheets(ThisWorkbook.Sheets.Count) 'last one is the copied one
'give it a new name (use the text in Textbox1 as name)
NewWorksheet.Name = Me.Textbox1.Text
End Sub

Hide/unhide sheet with specific name using VB

I would like to write function, that will hide all sheets in my workbook where sheet name begin with specific characters (sheet name will begin with characters: frm -> frmList, frmCheck, frmLoad, ...).
Then I would like to show/unhide specific sheet when I will call them. Let say that I am in Sheet1 and I would like to show (open) frmList (when go back to Sheet1, frmList should became invisible again).
Thanks.
What I do was to put code (for hidining)
Private Sub Worksheet_Deactivate()
Me.Visible = xlSheetVeryHidden
End Sub
in every sheet I would like to hide. Is there any option to use for all shets where name begin with specific characters (frm)?
For unhiding sheets I use:
Private Sub Worksheet_FollowHyperlink(ByVal Target As Hyperlink)
Dim shtName As String
'shtName = Target.Name
shtName = Left(Target.SubAddress, InStr(1, Target.SubAddress, "!") - 1)
Sheets(shtName).Visible = xlSheetVisible
Sheets(shtName).Select
End Sub
EDIT with loop
Ok, I loop for sheet name and hide them.
Dim ws As Worksheet
For Each ws In ActiveWorkbook.Worksheets
If ws.name Like "obr" & "*" Then
'''ws.Range("A1").Interior.ColorIndex = 37
' ws.Me.Visible = xlSheetVeryHidden
ws.Visible = xlSheetHidden
End If
Next ws
If I use as Private Sub Workbook_SheetChange(ByVal Sh As Object, ByVal Target As Range) I can not update my forms, because every time I change something inn those sheet it hide it(when press enter/return). How can I set, that if sheet is active, will not hide after pressing enter. It should hide only when go back to other sheet via hyperlink (click on text with hyperlink to "main" sheet) or just click on other sheet name.

VBA Add second Sheet with same Name

I have a CommandButton which opens a UserForm and create a copied Sheet with the name of the ComboBox Value.
This is My Code:
Private Sub CommandButton1_Click()
[UserForm1].Show ' Open UserForm
End Sub
Private Sub CommandButton2_Click()
Dim ws As Worksheet
ActiveWorkbook.Sheets("Sheet1").Visible = True ' Unhide Sheet
Sheets("Sheet1").Copy _
Before:=ActiveWorkbook.Sheets("Sheet1") ' Copy Sheet
Set ws = ActiveSheet
ws.Name = ComboBox1.Value ' Name Sheet
[UserForm1].Hide ' Close UserForm
ActiveWorkbook.Sheets("Sheet1").Visible = False ' Hide Sheet again
End sub
Now my problem is, if there are two machines with name "Machine Type 1" Excel gets an Error. So what do i have to change in my code, that the second sheet would named e.g. "Machine Type 1 (2)?
Thanks for your help.
you could try this
Private Sub CommandButton1_Click()
If IsSheetThere(ComboBox1.Value) Then 'if some sheet with chosen name already there
Sheets(ComboBox1.Value).Copy Before:=Sheets(10) ' copy the existing sheet
With ActiveSheet 'reference just copied sheet
.UsedRange.Clear 'clear its content
Sheets("Sheet1").UsedRange.Copy ActiveSheet.Range("A1") ' copy Sheet1 content and paste into it
End With
Else 'otherwise
Sheets("Sheet1").Copy Before:=Sheets(Sheets.Count) ' make a copy of "Sheet1" sheet
ActiveSheet.Name = ComboBox1.Value 'and rename it as per chosen name
End If
Me.Hide
End Sub
Function IsSheetThere(shtName As String) As Boolean
On Error Resume Next
IsSheetThere = Not Sheets(shtName) Is Nothing
End Function
the code line:
Sheets(ComboBox1.Value).Copy Before:=Sheets(10) ' copy the existing sheet
is the one that leaves Excel the burden of somehow "counting" the number of already existing sheets with the chosen name, and name the new one appropriately
You can use the following sub which calls the below function, just apply the same logic using .Copy
Sub create_new_sheet_with_name(name As String, wb As Workbook, aftersheet As Variant)
Dim i As Integer
i = 2
If sheet_name_exists(name, wb) Then
Do While sheet_name_exists(name & " (" & i & ")", wb)
i = i + 1
Loop
wb.Sheets.Add(after:=aftersheet).name = name & " (" & i & ")"
Else
wb.Sheets.Add(after:=aftersheet).name = name
End If
End Sub
Function sheet_name_exists(name As String, wb As Workbook) As Boolean
For Each sheet In wb.Worksheets
If sheet.name = name Then
sheet_name_exists = True
Exit Function
End If
Next sheet
sheet_name_exists = False
End Function
here's an example of how to use the sub:
Sub test()
create_new_sheet_with_name "hi", ThisWorkbook, ThisWorkbook.Sheets(1)
'this adds a new sheet named "hi" to thisworkbook after thisworkbook.sheets(1)
End Sub
Technically this isn't an answer to this question... but it's better because it will help you solve this and many other coding tasks on your own.
There is a simple way to create VBA code for most basic tasks.
If there's something Excel can do that you want to be able to do programmatically, just Record a Macro of yourself performing the action(s), and then look at the code that Excel generated.
I have a terrible memory, I can't remember commands I used yesterday. So it's not only quicker and less frustrating for others for me to figure it out myself, but the more often I do that, the quicker I'll learn (without asking others to do the thinking for me on a basic question).
I fact, I'm guess that the majority of veteran VBA coders learned at least partly by analyzing recorded macros. I know I did.

go to specific cell when a worksheet is selected

I want to go to specific cell when a worksheet is selected
Private Sub Worksheet_Cellselection()
ActiveSheet Goto:="D5"
End Sub
That one does not work
You need to use the Worksheet_Activate event of the relevant worksheet:
Private Sub Worksheet_Activate()
Range("D5").Select
End Sub
To use for several worksheets in a Workbook, move the code to Workbook_SheetActivate evenrt (inside the Workbook level):
Private Sub Workbook_SheetActivate(ByVal Sh As Object)
Select Case Sh.Name
Case "Sheet1", "Sheet2", "Sheet4" '<-- run it only for sheet's with these names
Range("D5").Select
End Select
End Sub
Application.Goto ActiveSheet.Range("D5")

Resources