Could I do without the commandbutton1 in my userform? - vba

I have a vba code for a userform in Excel. This userform allows me to display a listbox which shows all the worksheets available... Then after selecting the desired worksheet in my listbox and by clicking in my userform one button called " CommandButton1", it selects me the desired worksheet... However I would like simply by selecting and clicking on my desired worksheet in my listbox, it selects me the desired worksheet( In this way, i would no need any more to click on my button " CommandButton1" in my userform to select my desired worksheet)...If someone could help me with that, it would be really wonderful.. Many thanks in advance.Xavi please find my code below:
Sub CommandButton1_Click()
Worksheets(ListBox1.Value).Select
End Sub
Sub UserForm_Initialize()
Dim n As Integer
Dim msg As String
On Error GoTo Exit
Do
n = n + 1
ListBox1.AddItem Sheets(n).Name
Loop Until n = Worksheets.Count
If ListBox1.Value.Selected Then
CommandButton1_Click = True
Else
CommandButton1_Click = False
End If
Exit:
End Sub

all you need is ListBox Click event handler:
Option Explicit
Private Sub ListBox1_Click()
With Me.ListBox1
If .ListIndex <> -1 Then Worksheets(.Value).Select
End With
End Sub
Sub UserForm_Initialize()
Dim n As Integer
Do
n = n + 1
ListBox1.AddItem Sheets(n).Name
Loop Until n = Worksheets.Count
End Sub
BTW you UserForm_Initialize() can be a little simplified as follows
Sub UserForm_Initialize()
Dim sht As Worksheet
For Each sht In Worksheets
ListBox1.AddItem sht.Name
Next
End Sub

Related

How to make Excel print selective tabs using VBA?

I already coded my Excel workbook to print out all of my selective sheets that I need all at once. However, there are times where I will only need it to print specific sheets instead of all of them. Is there a way that before I print I can have my code ask me what range of sheets I want to print so I am not getting all 45 when I just need 7? Thank you in advance.
Chris
Sub PrintWorksheets()
Application.ScreenUpdating = False
Dim ws As Worksheet
For Each ws In ThisWorkbook.Worksheets
If ws.Name <> "Feedback Data" Then
If ws.Visible = xlSheetVisible Then
ws.PrintOut
End If
End If
Next ws
Application.ScreenUpdating = True
MsgBox "All charts have been printed Mark"
End Sub
Here's an example of a UserForm where we populate a ListBox with the names of all sheets in the file:
Code behind the UserForm:
Dim i As Long
Private Sub UserForm_Initialize()
For i = 1 To ActiveWorkbook.Sheets.Count
ListBox1.AddItem ActiveWorkbook.Sheets(i).Name
Next i
End Sub
Private Sub btnPrint_Click()
For i = 0 To ListBox1.ListCount - 1
If ListBox1.Selected(i) Then
ActiveWorkbook.Worksheets(ListBox1.List(i)).PrintOut
End If
Next i
End Sub
Private Sub btnCancel_Click()
Unload Me
End Sub
Naturally, there are other facets to this, such as changing the ListBox's MultiSelect property to 1 (to allow multiple sheets to be selected), and in my example I rename my buttons out of practice. But this is how you would solve your problem, in theory.
You could try to create more subroutines, each having different predefined set of sheets to select. Examples:
Public Sub selectSheets_1()
Dim arrayOfNames As Variant
arrayOfNames = Array(ws1.Name, ws2.Name, ws4.Name)
ThisWorkbook.Sheets(arrayOfNames).Select
End Sub
Public Sub selectSheets_2()
Dim arrayOfNames As Variant
arrayOfNames = Array(ws8.Name, ws15.Name, ws25.Name, ws35.Name, ws45.Name)
ThisWorkbook.Sheets(arrayOfNames).Select
End Sub
And so on...
Where ws# is the codename of sheet.

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?

Excel VBA: ListBox-UserForm Variable creation issue

Checked other similar questions on other websites, but could not find a solution.
I am trying to generate variables from the contents of a listbox-userform. The contents in the list are the names of workbooks. The first piece of code shows you how I generate the contents of the list for your reference. The second piece of code is the one with the issue.
Private Sub CommandButton1_Click()
Dim wb As Workbook
For Each wb In Workbooks
With ListBox1
.AddItem (wb.Name)
End With
Next wb
lbl_Exit:
End Sub
I am getting a Object Required error on the For Each line below. This piece of code resides in the Userform.
Private Sub CommandButton3_Click()
Dim MainBook As Workbook
Dim ListBox1 As ListBox
For Each Item In ListBox1
If Item.Name Like "Aggregate" Then
Item.Select
Set MainBook = Selection
End If
Next
End Sub
Note: I read that Item is a property of a ListBox which is where I got that from.
Is this what you are trying?
Private Sub CommandButton1_Click()
Dim wb As Workbook
For Each wb In Workbooks
With ListBox1
.AddItem (wb.Name)
End With
Next wb
End Sub
Private Sub CommandButton2_Click()
Dim MainBook As Workbook, i as Long
For i = 0 To (ListBox1.ListCount -1)
If ListBox1.List(i) Like "Aggregate" Then
Set MainBook = Workbooks(ListBox1.List(i))
MainBook.Activate
Exit For
End If
Next
End Sub

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.