Select next item from combobox and click on a button Excel VBA - excel

Have a combobox & command button placed on excel sheet. Combobox will have some items listed, say it have 1, 2, 3, 4, 5. When the combobox is loaded for the first time, by default first value ie 1 will be selected.
Now using a VBA macro, I want to select next value from the combobox list (ie 2) and click on the command button.
I googled this but unfortunately, not getting what I am expecting.
Here is what I have so far, but it dont do what I am expecting (Explained above): Getting an error message as Object doesn't support this property or method on line If Worksheets("QC Update").ComboBox1.SelectedIndex < ComboBox1.Items.Count - 1 Then
Sub Select_Next_Items()
If IsEmpty(Range("A9").Value) = True Then
If Worksheets("QC Update").ComboBox1.SelectedIndex < ComboBox1.Items.Count - 1 Then
ComboBox1.ListIndex = 0 ' select first Item in listbox
ComboBox1.ListIndex = ComboBox1.ListCount - 1 ' selects last item
Set ComboBox1.SelectedIndex = Worksheets("QC Update").ComboBox1.SelectedIndex + 1
Set ComboBox1.ListCount = 0
End If
End If
End Sub

hope you guys don't feel offended here, as I have a more clearer and a more straight forward answer.
ComboBox1.ListIndex = ComboBox1.ListIndex +1
Here is a more complete ones. We have to take into account when it is at the end of the list therefore
If ComboBox1.ListIndex = ComboBox1.ListCount -1 Then
ComboBox1.ListIndex =1
Else
ComboBox1.ListIndex = ComboBox1.ListIndex +1
I hope my reply is helpful to most of you especially those who are new to Vba and need to use it urgently.
This is simple to understand if you have solid background on programming in C++ / java

I wonder if this is your intention.
Sub Select_Next_Item()
' 07 Apr 2017
Dim Ws As Worksheet
Dim Cbx As OLEObject
Dim Ix As Integer
Set Ws = Worksheets("QC Update")
If IsEmpty(Ws.Range("A9").Value) = True Then
Set Cbx = Ws.OLEObjects("ComboBox1")
With Cbx.Object
Ix = .ListIndex + 1
If Ix = .ListCount Then Ix = 0
If .ListCount Then .ListIndex = Ix
End With
End If
End Sub
If the cell A9 is found empty, the code will look at the "ComboBox1" (and will crash if it isn't found on the same, specified worksheet). It will change the selection in that combobox to the next value in the list. But if it was already at the last list item it will select the first, and if there are no list items in the combobox it will do nothing.

Finally this issues is resolved with below code,
Set Cbx = Worksheets("QC Update").OLEObjects("ComboBox1")
With Cbx.Object
Ix = .ListIndex + 1
If Ix = .ListCount Then Ix = 0
If .ListCount Then .ListIndex = Ix
End With

I share my simple solution
Try
ComboBoxDireccion.SelectedIndex = ComboBoxDireccion.SelectedIndex + 1
Catch ex As Exception
ComboBoxDireccion.SelectedIndex = 0
End Try

Related

loop through all comboboxes in userform and validate with name and make them visible

I have a userform in which pages and then on one page contain a lot of comboboxes all of them have a pattern in their name as per their location for example in first row I have 3 comboboxes their names are:
AO11, AO12, AO13
Second row has 04 comboboxes with following names
AO21, AO22, AO23, AO24
Third row has 04 Comboboxes with following names
AO31, AO32, AO33, AO34
and so on till 12~15 Comboboxes
X represents row number when which will start with X=1 because first row will always be visible.
once user press AddNewCMD it should make visible the next row of comboboxes with the following code:
Private Sub AddNewCMD_Click()
If X = 2 Then
Me.AO21.Visible = True
Me.AO22.Visible = True
Me.AO23.Visible = True
Me.AO24.Visible = True
X = X + 1
ElseIf X = 3 Then
Me.AO31.Visible = True
Me.AO32.Visible = True
Me.AO33.Visible = True
Me.AO34.Visible = True
X = X + 1
End If
End Sub
in AO21
2 represents row number
1 represent first combo in row two
however I realize that it will be very long code as if I add further rows in therefore I am search for a way that can loop through each comboboxes and validate x with its name and make them visible?
same goes for hiding the comboboxes.
Please, copy the next code in the userForm code module:
Option Explicit
Private nextRow As Long
Private Sub AddNewCMD_Click()
Dim i As Long, ctrl As MSForms.Control, boolVis As Boolean
If nextRow = 0 Then
nextRow = 2
Else
nextRow = nextRow + 1
End If
Debug.Print nextRow
For i = 0 To Me.MultiPage1.Pages(0).Controls.count - 1
Set ctrl = Me.MultiPage1.Pages(0).Controls(i)
If TypeOf ctrl Is MSForms.ComboBox Then
If CLng(Right(ctrl.Name, Len(ctrl.Name) - 2)) > 13 Then
Debug.Print ctrl.Name, ctrl.Visible
If CLng(Mid(ctrl.Name, 3, 1)) = nextRow Then
ctrl.Visible = True: boolVis = True
End If
End If
End If
Next i
If Not boolVis Then MsgBox "The row " & nextRow & " does not exist..."
End Sub
ClickingAddNewCMD button will make the next combos row visible. When the existing rows are all made visible, a message stating that no any row available will be raised.
You did not answer my clarification questions... But if only one such combo row should be visible (except the first one, or including), I can make a function to determine it, but this can be done only if you supply a logic algorithm based on what to proceed.

Excel VBA - Link a Label and a Checkbox

I have the following userform:
Using the code below I can save the names of each selected checkbox into a sheet. The value will be saved in the same column, but on different rows (of course), as more than 1 checkbox can be selected.
Dim indProdWs As Worksheet
Dim ctl As Control
Dim i As Long
Set indProdWs = tWb.Worksheets("INDICATION-PRODUCT")
i = 4
' This is the row where i want to save the first value
For Each ctl In seg_multipage.Pages(1).Controls
If TypeName(ctl) = "CheckBox" Then
If ctl.Value = True Then
indProdWs.Cells(i, 9) = ctl.Caption: i = i + 1
End If
End If
Next ctl
However, as you can see in the first image, for each row of products there's a label.
This is what I want to accomplish:
If Product 22 in the second row is selected, then I want the name to be saved on the cell with the following format:
Label2 - Product22
Or if Product 51 in the second row is selected:
Label 5 - Product 51
As you can see, the label number always matches the first digit of the product. I tried using that as a variable, but I haven't been successful.
Thank you for any help you can give me!
is the name actually "Product22" or this just an example? – Siddharth Rout 6 mins ago
#SiddharthRout just an example, but the format is similar. An actual name is seg_cb_selInd_22 (for example). – soraia635 1 min ago
Is this what you are trying?
Change the For - Next code to the below
For Each ctl In seg_multipage.Pages(1).Controls
If TypeName(ctl) = "CheckBox" Then
If ctl.Value = True Then
indProdWs.Cells(i, 9) = Controls("seg_l_selInd_" & _
GetNumber(ctl.Name)).Caption & _
" - " & _
ctl.Name
i = i + 1
End If
End If
Next ctl
and then add this function to your code
Private Function GetNumber(s As String)
Dim numb As Long
Dim i As Long
For i = 1 To Len(s)
Select Case Mid(s, i, 1)
Case 0 To 9
numb = Mid(s, i, 1)
Exit For
End Select
Next
GetNumber = numb
End Function
Note: This function assumes that you will pass an Alphanumeric string to it.

VBA - Excel Listbox - Look for Duplicates when Adding Items to Second Listbox

So I am new to the forms side of the VBA coding and I seem to be struggling a bit with this one.
What I have did was follow this tutorial:
https://www.excel-easy.com/vba/examples/multiple-list-box-selections.html
And I have adapted it in a way that suits my needs, but now I am having an issue or two that I do not understand how I can resolve.
The code in the tutorial adds two list boxes to a form and then the add button copy items from the first listbox to the second and the remove button removes items from the second listbox.
The problem is that you can add a specific item more than once, and considering I would like to use the values in the second listbox, this is a problem as I need only unique values.
The code below is what I have come up with so far, but I am getting an error:
Private Sub btn_Add_Filter_Click()
For i = 0 To lbx_Filters_List.ListCount - 1
If lbx_Filters_List.Selected(i) = True Then
For X = 0 To lbx_Filters.ListCount
If Not IsError(lbx_Filters.List(X)) Then
mVal = 0
If lbx_Filters.List(X) <> "" And lbx_Filters.List(X) = lbx_Filters_List.List(i) Then
myVal = 1
End If
End If
If myVal = 0 Then
lbx_Filters.AddItem _
lbx_Filters_List.List(i)
End If
Next X
End If
Next i
End Sub
The error occurs the second time I try and add the same item from the first listbox and what happens is that the second for loop will loop once and on the second loop it throws an error on this line:
If Not IsError(lbx_Filters.List(X)) Then
Error being:
Could not get the list property. Invalid property array index
I eventually (with the help of the comments above) solved the issue. Thank you to all who assisted.
Private Sub btn_Add_Filter_Click()
Dim Size As Integer
Size = lbx_Filters.ListCount
Dim ListBoxContents() As String
Dim ListBoxC() As Variant
Dim i As Integer, y As Integer, X As Integer, myVal As Integer, lItem As Integer
myVal = 0
For i = 0 To lbx_Filters_List.ListCount - 1
If lbx_Filters_List.Selected(i) = True Then
If Size > 0 Then
For lItem = 0 To lbx_Filters.ListCount - 1
For X = 0 To lbx_Filters_List.ListCount - 1
If Not IsError(lbx_Filters_List.List(X)) And lbx_Filters.List(lItem) = lbx_Filters_List.List(i) Then
myVal = 1
End If
Next X
Next lItem
End If
If myVal = 0 Then
lbx_Filters.AddItem _
lbx_Filters_List.List(i)
End If
End If
Next i
End Sub

Remove Item from Excel Listbox

I need to remove items from a Listbox using data from Range under certain conditions. I don't want to delete data in the Worksheet the Listbox is based on.
Here is an excerpt of my code:
Me.LstWSource.RowSource = ""
If Len(rRange.Offset(1, 0).Formula) > 0 Then
Set rRange = ThisWorkbook.Sheets(G_sNameReferenceS).Range(rRange.Offset(1, 0), rRange.End(xlDown))
With Me.LstWSource
.ColumnWidths = "28pt"
.RowSource = rRange.Address
.ListIndex = -1
End With '>>>
End If
'>>>>>>>>>>>>>>>>>>>>>>>>
sRet = fG_SortingBasicS("lstYear", "DESC")
'>>>>>>>>>>>>>>>>>>>>>>>>
For i = Me.LstWSource.ListCount - 1 To 0 Step -1
'>> current string condition to delete Item <<
If Me.LstWSource.List(i) > CStr(Year(G_datJourTraitee)) Then
Me.LstWSource.RemoveItem (i)
End If
Next i
The error is triggered by the RemoveItem.
If you use .RowSource to fill your ListBox you cannot remove list items from the list.
Therefore you need to fill your list using LstWSource.AddItem. Loop through your range and add each item to your ListBox based on your criteria. Also see Adding items in a Listbox with multiple columns.
For additional information and bring my definite solution related to slowing populating : I used once the read of Range cells to populate a dynamic array. Then, I use this array to exclude or include lines in another second array.
These are lines to be considered :
J = 1
For i = LBound(G_varListYears) To UBound(G_varListYears)
If G_varListYears(i) <= CStr(Year(G_datJourTraitee)) Then
'>>>
ReDim Preserve vListTMP(J)
vListTMP(J) = G_varListYears(i)
J = J + 1
'>>
ElseIf (Me.chkNextYear = True) And ((Month(G_datJourTraitee) = 11 Or Month(G_datJourTraitee) = 12) And (G_varListYears(i) = CStr(Year(G_datJourTraitee) + 1))) Then
'>>>
ReDim Preserve vListTMP(J)
vListTMP(J) = G_varListYears(i)
J = J + 1
'>>
Else
'>>
End If
Next i
With Me.LstWSource
.ColumnWidths = "28pt"
.List = vListTMP()
.ListIndex = -1
End With '>>>
Hope it'll help too.

Allow listbox to display no results when ListBox.RowSource returns no results

I'm currently populating a ListBox in a form with the following code:
'Populate In-Form Table
With ListBox_InFormTable
.ColumnCount = 4
.ColumnWidths = "100;100;100;50"
.RowSource = ws.Range("MasterDataTable").SpecialCells(xlCellTypeVisible).Address
End With
However, I'm also actively filtering what's displayed in the listbox with other fields in the form. This works fine except when I filter out all the results. Instead of getting an error that states: "No cells were found." I'd rather just leave the in-form table blank.
Any help would be greatly appreciated, I've been banging my head against this one for a while now.
Thanks!
You can try something like this...
Dim n As Long
With ListBox_InFormTable
.ColumnCount = 4
.ColumnWidths = "100;100;100;50"
On Error Resume Next
n = ws.Range("MasterDataTable").SpecialCells(xlCellTypeVisible).Rows.Count
On Error GoTo 0
If n > 0 Then
.RowSource = ws.Range("MasterDataTable").SpecialCells(xlCellTypeVisible).Address
End If
End With
In case you are filtering an Excel Table, you may count the filtered rows as below...
Dim n As Long
With ListBox_InFormTable
.ColumnCount = 4
.ColumnWidths = "100;100;100;50"
On Error Resume Next
n = ActiveSheet.ListObjects("MasterDataTable").Range.Resize(, 1).SpecialCells(xlCellTypeVisible).Count
On Error GoTo 0
If n > 0 Then
.RowSource = ws.Range("MasterDataTable").SpecialCells(xlCellTypeVisible).Address
End If
End With
End Sub

Resources