Excel VBA: Move ActiveCell to Row of Newly Inactive Sheet - vba

When I move from Sheet1 to Sheet2, what VBA can I use to have the activecell of Sheet2 be the same row as was active on Sheet1 when I switched?
For example: I have Cell B7 active on Sheet1. When I switch to Sheet2, the activecell moves to the 7th row, (and does not change columns from what it was the last time I was on Sheet2).

After really debugging hard on event sequences, I said "Eureka!". The following does what you ask:
Private activeRow As Integer, activeCol As Integer
Private sema4 As Integer
Private Sub Workbook_SheetDeactivate(ByVal Sh As Object)
If (sema4 > 0) Then Exit Sub
sema4 = 1
Sheets(Sh.Name).Activate
End Sub
Private Sub Workbook_SheetActivate(ByVal Sh As Object)
If (sema4 = 1) Then
activeRow = Selection.row
activeCol = Selection.Column
sema4 = 2
Exit Sub
ElseIf (sema4 = 2) Then
sema4 = 3
Sheets(Sh.Name).Activate
Exit Sub
ElseIf (sema4 = 3) Then
ActiveSheet.Cells(activeRow, activeCol).Select
sema4 = 0
End If
End Sub
Again, attach in VB editor to the Workbook.

Although the question received a downvote, it is absolutely not trivial. I have only been able to research a partial answer.
Attach the following code to the Workbook (double click on ThisWorkbook in VBA Project Explorer):
Private activeRow As Integer, activeCol As Integer
Private Sub Workbook_SheetDeactivate(ByVal Sh As Object)
activeRow = Selection.Row
activeCol = Selection.Column
End Sub
Private Sub Workbook_SheetActivate(ByVal Sh As Object)
ActiveSheet.Cells(activeRow, activeCol).Select
End Sub
The intention is clear: get the selection on the sheet being deactivated and then set the selection on the sheet being acivated.
There only are two problems:
Excel has only one Selection and that is the current selection on the active sheet.
The deactivate event occurs after the sheet is deactived and the new sheet activated.
As a result, it is not possible to get the last position of the user on the sheet that got deactivated and so we can't set it on the sheet being activated.
Anyone any ideas?

Related

Excel vba when adding or deleting sheet in workbook, show/hide button in main sheet

I have a button with a simple macro that deletes certain sheets.
I'd like to show this button only when those sheets are actually there (I can use worksheets.count because I have 2 "permanent" sheets; if > 2 then I know I have a new sheet and I want to show the button to delete it if I want to).
I think I have to use "Workbook.SheetChange event" because "Worksheet.Change event" doesn't seem to work for me in this case.
Private Sub Workbook_SheetChange(ByVal Sh As Object, ByVal Target As Range)
Dim foglio_parametri As Worksheet
Set foglio_parametri = ThisWorkbook.Worksheets("PARAMETRI") 'my main sheet where I want to show/hide the button
Application.ScreenUpdating = True
If Application.Worksheets.Count > 2 Then
foglio_parametri.CommandButton2.Visible = True
Else
foglio_parametri.CommandButton2.Visible = False
End If
End Sub
Thank you very much for your time.
I will not use your names as they are in a foreign language I do not understand .
Let's assume the button you are talking about is in a sheet with the name sheet3 which also has the codename sheet3. The button itself has the name CommandButton1. Let's further assume the certain sheets you are talking about have the names sheet4 and sheet5 then I would add the following code to the workbook module
Option Explicit
Private Sub Workbook_Open()
Sheet3.HidecmdBtn
End Sub
Private Sub Workbook_SheetActivate(ByVal Sh As Object)
If Sh.Name = "Sheet3" Then
Sheet3.HidecmdBtn
End If
End Sub
In the worksheet module of sheet3 you have the following code
Option Explicit
Private Sub CommandButton1_Click()
' Your code goes here
' In case your code deletes the sheets you have to hide the button
HidecmdBtn
End Sub
Sub HidecmdBtn()
Dim Sh As CommandButton
' My button is located on sheet 3 and has the name "CommandButton1"
Set Sh = CommandButton1
Dim sh1Name As String
Dim sh2Name As String
sh1Name = "Sheet4"
sh2Name = "Sheet5"
If SheetExists(sh1Name) Or SheetExists(sh2Name) Then
Sh.Visible = msoTrue
Else
Sh.Visible = msoFalse
End If
End Sub
In a normal module you have
Public Function SheetExists(SheetName As String, Optional wrkBook As Workbook) As Boolean
If wrkBook Is Nothing Then
Set wrkBook = ActiveWorkbook 'or ThisWorkbook - whichever appropriate
End If
Dim obj As Object
On Error GoTo HandleError
Set obj = wrkBook.Sheets(SheetName)
SheetExists = True
Exit Function
HandleError:
SheetExists = False
End Function

Automatically open an excel file to cell A1 in all worksheets (using VBA)

I am trying to write VBA code so that whenever I open any file in excel, it automatically goes to Cell A1 in all sheets (no matter what cells were selected when it was last saved). I found something online that suggested putting the following code in my Personal .xlsb project:
Sub kTest()
Dim i As Long, s() As String, a As String, n As Long
With ActiveWorkbook
For i = 1 To .Worksheets.Count
a = a & .Worksheets(i).Name
n = n + 1
ReDim Preserve s(1 To n)
s(n) = .Worksheets(i).Name
If Len(a) > 224 Then
.Worksheets(s).Select
.Worksheets(s(1)).Activate
[a1].Select
n = 0: a = "": Erase s
End If
Next
If Len(a) Then
.Worksheets(s).Select
.Worksheets(s(1)).Activate
[a1].Select
End If
Application.Goto .Worksheets(1).Range("a1")
End With
End Sub
But nothing happens when I open a file. Please help!
You cannot go to Cell A1 in every sheet. But if you would like to go to Cell A1 of a single sheet you could do the following.
Create a class ExcelEvents with the following code
Option Explicit
Private WithEvents App As Application
Private Sub App_WorkbookOpen(ByVal Wb As Workbook)
App.Goto Wb.Worksheets(1).Range("A1")
End Sub
Private Sub Class_Initialize()
Set App = Application
End Sub
And in ThisWorkbook add
Option Explicit
Private xlApp As ExcelEvents
Private Sub Workbook_Open()
Set xlApp = New ExcelEvents
End Sub
Save the workbook, re-open it and the code in the workbook_open event will run and that means as soon as you open another workbook the code will goto cell A1 of sheet 1
EDIT If you really mean to select A1 in every single sheet you could change the code as follows
Private Sub App_WorkbookOpen(ByVal Wb As Workbook)
Dim sh As Worksheet
App.ScreenUpdating = False
For Each sh In Wb.Worksheets
sh.Select
sh.Range("A1").Select
Next
App.Goto Wb.Worksheets(1).Range("A1")
App.ScreenUpdating = True
End Sub
A simple solution:
For Each Sheet In ActiveWorkbook.Worksheets
Sheet.Select
Range("A1").Select
Next
Using MicScoPau's loop through the worksheets
Place the following code in the ThisWorkbook module of Personal.xlsb:
You'll have to reopen excel for this to work the first time.
If your Personal.xlsb is hidden, then you will have some issues with the each sheet in activeworkbook.
Private WithEvents app As Application
Private Sub app_WorkbookOpen(ByVal Wb As Workbook)
For Each Sheet In ActiveWorkbook.Worksheets
Sheet.Select
Range("A1").Select
Next
End Sub
Private Sub Workbook_Open()
Set app = Application
End Sub

Excel VBA user form to display the sheet which is selected

I have created a userform which has a listbox (ListBox1)which list down the sheet names and I can double click on the list and it will take me to that sheet. I have a back button (CommandButton2) when I click on back button it will take me to the previous selected sheet.
I want to link my list box and back button so that when I click on back button the my listbox (ListBox1)should highlight the sheet where my back button (CommandButton2) has directed to.
Please find below my codes:
Private Sub UserForm_Initialize()
Dim Sh As Worksheet
'for each loop the add visible sheets
For Each Sh In ActiveWorkbook.Sheets
'add sheets to the listbox
Me.ListBox1.AddItem Sh.Name
Next Sh
End Sub
Private Sub ListBox1_DblClick(ByVal Cancel As MSForms.ReturnBoolean)
'declare the variables
' modifed code for ListBox double-click event, store the sheet name before switching to the selected item
Dim i As Long
LastSelectedSht = ActiveSheet.Name ' <-- save the current active sheet before selecting a new one
For i = 0 To ListBox1.ListCount - 1
If ListBox1.Selected(i) Then
Worksheets(ListBox1.List(i)).Activate
End If
Next i
End Sub
Private Sub CommandButton2_Click()
Dim TmpSht As String
TmpSht = ActiveSheet.Name ' <-- save the current active sheet
' select the previous sheet (stored in LastSelectedSht)
If LastSelectedSht = "" Then
MsgBox "Error, no sheet stored , is it your first time running ? "
Else
Sheets(LastSelectedSht).Select
End If
LastSelectedSht = TmpSht ' <-- use the temp variable to store the latest active sheet
' reset the userform
Unload Me
frmNavigation.Show
End Sub
No need for al those loops to seek selected item, you can simplify things a bit as follows:
Option Explicit
Dim LastSelectedSht As String '<--| use as UserForm scoped variable to store the name of "last" sheet selected
Private Sub UserForm_Initialize()
Dim Sh As Worksheet
With Me.ListBox1
'for each loop the add visible sheets
For Each Sh In ActiveWorkbook.Sheets
.AddItem Sh.Name 'add sheets names to the listbox
Next Sh
LastSelectedSht = ActiveSheet.Name ' <-- store the currently active sheet name as the "last" one
.Value = LastSelectedSht '<--| initialize listbox selection with the currently active sheet name
End With
End Sub
Private Sub ListBox1_DblClick(ByVal Cancel As MSForms.ReturnBoolean)
' modifed code for ListBox double-click event, store the sheet name before switching to the selected item
LastSelectedSht = ActiveSheet.Name
Worksheets(ListBox1.Value).Activate '<--| activate the sheet whose name has been dblclicked
End Sub
Private Sub CommandButton2_Click()
Sheets(LastSelectedSht).Activate
Me.ListBox1.Value = LastSelectedSht
' reset the userform
Unload Me
frmNavigation.Show
End Sub
This sub will change the selected item in the list box.
Private Sub SetListBox(Lbx As MSForms.ListBox, _
Itm As String)
Dim i As Integer
With Lbx
For i = 0 To .ListCount - 1
.Selected(i) = Not CBool(StrComp(.List(i), Itm))
Next i
End With
End Sub
Call it from your procedure which activates the previous worksheet with a line of code like this one.
SetListBox ListBox1, TmpSht
Make sure that TmpSht holds the name of the newly activated sheet at the time you make the call or pass the name of that sheet instead of TmpSht.

How make Excel select the same cell when changing sheets?

I have Excel workbook with 3 sheets. I want to use a macro which will select the same cell when changing sheets.
Example:
I am in sheet1 cell A3 when I switch to sheet2. I want A3 in sheet2 to be selected. Same thing when I switch to sheet3.
Is it possible?
I tried using events sheet_activate, sheet_deactivate, and sheet_change. The last one is surely wrong.
You were close. This uses a module-level variable to store the ActiveCell address any time the SheetSelectionChange event fires:
Dim ActiveCellAddress As String
Private Sub Workbook_SheetActivate(ByVal Sh As Object)
Application.ScreenUpdating = False
Sh.Range(ActiveCellAddress).Activate
Application.ScreenUpdating = True
End Sub
Private Sub Workbook_SheetSelectionChange(ByVal Sh As Object, ByVal Target As Range)
ActiveCellAddress = ActiveCell.Address
End Sub
Here is a one-way example. If you start on Sheet1 and select either Sheet2 or Sheet3, you will stay on the same address as you were on Sheet1.
In a standard module, include the single line:
Public addy As String
In the Sheet1 code area, include the following event macro:
Private Sub Worksheet_SelectionChange(ByVal Target As Range)
addy = ActiveCell.Address
End Sub
In both the Sheet2 and Sheet3 code areas, include the following event macro:
Private Sub Worksheet_Activate()
If addy <> "" Then
Range(addy).Select
End If
End Sub
I use the following macro to select cell A1 on all sheets within a workbook. I assigned this macro to a button on a toolbar. You can modify it to make it work for when you change sheets.
Sub Select_Cell_A1_on_all_Sheets()
Application.ScreenUpdating = False
On Error Resume Next
Dim J As Integer
Dim NumSheets As Integer
Dim SheetName As String
CurrentSheetName = ActiveSheet.Name
NumSheets = Sheets.Count
For J = 1 To NumSheets
SheetName = Sheets(J).Name
Worksheets(SheetName).Activate
Range("A1").Select
Next J
Worksheets(CurrentSheetName).Activate

Using textboxes within userform to define variables?

I currently run a macro to compare the most recent sheet of data to the report immediately prior and highlight changes. It works fine on its own. Now, however, we would like to be able to compare selected sheets from any time period. My idea was to pop up a simple userform with two textboxes that the user can use to specify which two reports he wants to compare. I am quite lost though with the idea of trying to declare public variables; what I've got atm is:
Option Explicit
Public shtNew As String, shtOld As String, _
TextBox1 As TextBox, TextBox2 As TextBox
Sub SComparison()
Const ID_COL As Integer = 31 'ID is in this column
Const NUM_COLS As Integer = 31 'how many columns are being compared?
Dim rwNew As Range, rwOld As Range, f As Range
Dim X As Integer, Id
shtNew = CSManager.TextBox1
shtOld = CSManager.TextBox2
'Row location of the first employee on "CurrentMaster" sheet
Set rwNew = shtNew.Rows(5)
Do While rwNew.Cells(ID_COL).Value <> ""
Id = rwNew.Cells(ID_COL).Value
Set f = shtOld.UsedRange.Columns(ID_COL).Find(Id, , xlValues, xlWhole)
If Not f Is Nothing Then
Set rwOld = f.EntireRow
For X = 1 To NUM_COLS
If rwNew.Cells(X).Value <> rwOld.Cells(X).Value Then
rwNew.Cells(X).Interior.Color = vbYellow
rwNew.Cells(33) = "UPDATE"
Else
rwNew.Cells(X).Interior.ColorIndex = xlNone
End If
Next X
End If
Set rwNew = rwNew.Offset(1, 0) 'next row to compare
Loop
Call SUpdates
End Sub
My Suggestion would be to use Comboboxes instead of TextBoxes. Create a userform with two command buttons and two comboboxes and populate the comboboxes in the UserForm_Initialize() event using this code.
Private Sub UserForm_Initialize()
Dim ws As Worksheet
For Each ws In ActiveWorkbook.Sheets
ComboBox1.AddItem ws.Name: ComboBox2.AddItem ws.Name
Next
End Sub
And then use this code in the OK button to do the comparison.
Private Sub CommandButton1_Click()
Dim shtNew As Worksheet, shtOld As Worksheet
If ComboBox1.ListIndex = -1 Then
MsgBox "Please select the first sheet"
Exit Sub
End If
If ComboBox2.ListIndex = -1 Then
MsgBox "Please select the Second sheet"
Exit Sub
End If
Set shtNew = Sheets(ComboBox1.Value)
Set shtOld = Sheets(ComboBox2.Value)
'~~> REST OF THE CODE HERE NOW TO WORK WITH THE ABOVE SHEETS
End Sub
Private Sub CommandButton2_Click()
Unload Me
End Sub
HTH
Sid
For an easy fix, couldn't you just colour (sorry, I'm English!) the worksheets that you want to refer to, then do something like:
Sub ListSheets()
'lists only non-coloured sheets in immediate window
'(could amend to add to combo boxes)
Dim w As Worksheet
'loop over worksheets in active workbook
For Each w In Worksheets
If w.Tab.Color Then
'if tab color is set, print
Debug.Print w.Name
End If
Next w
Let me know if this solves your problem.