Excel VBA user form to display the sheet which is selected - vba

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.

Related

VBA - Hide certain column in every worksheet of workbook when checkbox is not selected

I am trying to hide every "A" column in my workbook when a certain checkbox in my user form is not selected.
I have 6 worksheets in my one workbook.
I have 6 checkboxes.
When a checkbox is not selected, I'd like to hide the column that it's associated with.
Ex: When the "Advice" checkbox is not checked, I'd like to hide the "A" column in EVERY worksheet in my workbook.
Thank you!
I tried this:
shtFinancial.Range("D").EntireColumn.Hidden = Not cbAdvice.Value
And this:
If cbAdvice.Value = True Then
shtFinancial.Range("D").EntireColumn.Hidden
Checkboxes in VBA are really funky. Here is one method:
Sub cbAdvice_Click()
Dim CheckBox As Shape, ws As Worksheet
Set CheckBox = Sheet1.Shapes("cbAdvice")
For Each ws In ActiveWorkbook.Worksheets
If CheckBox.OLEFormat.Object.Value = 1 Then
ws.Columns("A:A").EntireColumn.Hidden = False
Else
ws.Columns("A:A").EntireColumn.Hidden = True
End If
Next ws
End Sub
I created two active x control boxes "CheckboxColA" and "CheckboxColB" and gave them the following code for a change of state:
Sheet1("Worksheet Controls")
Private Sub CheckboxColA_Change()
Call changeColAVisiblity(CheckboxColA.Value, "A")
End Sub
Private Sub CheckBoxColB_Change()
Call changeColAVisiblity(CheckBoxColB.Value, "B")
End Sub
Then created the following code in "module1"
Sub changeColAVisiblity( _
cbState As Boolean, _
changeColumn As String)
Dim ws As Worksheet
For Each ws In ActiveWorkbook.Worksheets
'If statement Assumes sheet with contols should not change
If ws.Name <> "CheckBox Controls" Then
ws.Columns(changeColumn).Hidden = cbState
End If
Next
End Sub

Worksheet Change to run macro

My workbook contains several sheets, each with multiple checkboxes. All checkboxes in all worksheets have the linked cell in row 80. In a worksheet called "Info" I am using countif to count the total number of times the text "TRUE" occurs in row(s) 80 for all worksheets. The total is in Info!B8.
I need to call a macro each time cell Info!b8 changes. So in other words; every time a checkbox is clicked, the linked cell changes, cell Info!b8 goes up or down and I need a macro to run.
This is the code I am using, but it doesn't do anything. I have researched this and from what I can tell it should work??
Private Sub Worksheet_Change(ByVal Target As Range)
If Target.Address = "$B$8" Then
Call CreateFinalWorksheet
End If
End Sub
Assuming all your CheckBoxes are of Form Controls, with a bit of altering the CheckBox Creation, you can achieve what you want without the need of LinkedCell and CountIfs etc.
Example: CreateCheckBoxes() below will create a check box for each cell in Range("D1:D5"), Name it with a prefix and the cell address, assigns the Sub CheckBoxClicked when clicked.
In Sub CheckBoxClicked(), it will go through all worksheets (except named "Info"), then increment a counter if the value of checkbox named ending D3 is 1 (ticked). After that, if threshold is met, it calls the Sub CreateFinalWorksheet().
Option Explicit
Private Const ChkBoxPrefix As String = "cbx_"
Private Const ThresholdToCreateFinalWorksheet As Long = 3
Sub CreateChkBoxes()
Dim myCBX As CheckBox, c As Range
For Each c In Range("D1:D5") 'rngCB
With c
Set myCBX = ActiveSheet.CheckBoxes.Add(Top:=.Top, Width:=.Width, Height:=.Height, Left:=.Left)
End With
With myCBX
.Name = ChkBoxPrefix & c.Address(0, 0)
.Caption = "Check Box " & c.Address(0, 0) 'strCap
.OnAction = "CheckBoxClicked" ' "CheckBox_Click"
End With
Next c
End Sub
Sub CheckBoxClicked() ' CheckBox_Click()
Dim oWS As Worksheet, lChecked As Long
On Error Resume Next ' Just in case the named CheckBox does not exist
lChecked = 0
For Each oWS In ThisWorkbook.Worksheets
If oWS.Name <> "Info" Then
' If you need to keep track of more than 1 checkbox in each worksheet, go through them
' If you need all of them to be checked before CreateFinalWorksheet, exit when a checkbox.value = 0
With oWS.CheckBoxes(ChkBoxPrefix & "D3") ' <-- Change to what you need to keep track of
lChecked = lChecked + IIf(.Value = 1, 1, 0)
End With
End If
Next
On Error GoTo 0
If lChecked >= ThresholdToCreateFinalWorksheet Then CreateFinalWorksheet
End Sub
Private Sub CreateFinalWorksheet()
Debug.Print "CreateFinalWorksheet()"
End Sub
Alternatively you put the event Sub Worksheet_Calculate() into Info module, and check if the Info!B8 is large enough to call CreateFinalWorksheet.

create a backbutton in excel vba userform to go to the previous active sheet

I have created a userform frmNavigation which has a ListBox1, which will list down all the worksheets present in my workbook and I can double click on any of worksheet listed in the listbox and go to that sheet.
Now as I have close to 50 worksheets so I double click from the list appearing in ListBox1 and go to that sheet but now I want a back button "CommandButton2" so that it can take me back to my previous active sheet.
I have created a code but its not working.
Private Sub CommandButton2_Click()
Application.ScreenUpdating = False
Dim i As Integer, Sht As String
'for loop
For i = 0 To ListBox1.ListCount - 1
'get the name of the selected sheet
If ListBox1.Selected(i) = True Then
Sht = ListBox1.List(i - 1)
End If
Next i
'select the sheet
Sheets(Sht).Select
'reset the userform
Unload Me
frmNavigation.Show
End Sub
Try the code below, I am not sure how to explain my logic of the code below, I tired my best to describe it in the code comments.
I've modified also the ListBox1_DblClick code event, to save the latest ActiveSheet before you Select the new sheet.
Code
Option Explicit
Dim LastSelectedSht As String ' Variable at module level, to store the name of the last selected sheet
'===================================================================
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
'===================================================================
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
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 UserForm_Activate()
Dim ws As Worksheet
For Each ws In ThisWorkbook.Sheets
Me.ListBox1.AddItem ws.Name
Next ws
End Sub

Excel VBA: Move ActiveCell to Row of Newly Inactive Sheet

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?

Vba UserForm combobox items don't apear till i click on the userform

I have a command button, when i click it, it shows a customized userform which contains a combobox with items taken from a sheet cells. the user is suppose to press the command then the userform appears, he needs to select one item from the list, the item is a sheet name in different workbook, accordingly it will import the data from that sheet. however i am facing a problem:
when the userform appears, i click on the combobox it shows no items, then if i click once on the userform then check the combobox again it shows the items correctly, if i click again on the userform, the combobox items will be doulbled! if i selected an item it works perfectly.
So what i want to achieve is: i want the combobox to show the items directly without clicking on the userform.
the code is this:
In the userform:
Private Sub UserForm_Click()
Dim mlf As Workbook
Dim adad As Long
Dim mada As String
Dim lastRow As Long
Set mlf = ActiveWorkbooklastRow = Sheet3.Cells(Rows.Count, 1).End(xlUp).Row
For adad = 1 To lastRow
mada = Sheet3.Cells(adad, 1)
With ComboBox1
.AddItem mada
End With
Next
End Sub
Private Sub cmdOkay_Click()
'Verify that an item was selected
If Me.ComboBox1.BoundValue = vbNullString Then
MsgBox "You did not choose an item!", vbOKOnly
Exit Sub
Else
MsgBox "You have selected " & Me.ComboBox1.BoundValue, vbOKOnly
Sheet3.Cells(1, 2) = Me.ComboBox1.BoundValue
End If
Unload Me
End Sub
In the CommandButton
Dim testbook As Workbook
Set testbook = ThisWorkbook
Set database = Workbooks.Open(Filename:=myPath & myFile)
testbook.Worksheets("Sheet4").Range("A1:B5").Clear
With UserForm1
.Caption = "Settings of the test"
End With
Dim lo As Integer
For lo = 1 To database.Sheets.Count
testbook.Sheets("Sheet4").Cells(lo, 1) = database.Worksheets(lo).Name
Next
UserForm1.Show
That is because you are telling it to do that on the click event.
Change
Private Sub UserForm_Click()
to
Private Sub UserForm_Initialize()
Once you change this, the combobox issue will also go away.