Comparison of two listbox in VBA - vba

I am new at VBA.So kindly help me on this matter.
My UserForm has two ListBox controls in it, each with two columns. For example, ListBox1
Name Item
A 20
B 30
and listbox2:
Name Item
A 20
B 40
When I click a CommandButton, the procedure below attempts to compare both ListBox controls and returns whether or not the data in each column of data is correct. I believe the best approach would be to first compare Column 1 of ListBox1 with Column 1 of ListBox2. If those are identical, then compare the second columns of both ListBox controls. The procedure is supposed to return a MsgBox that says "Correct" if all columns are identical. Otherwise, the program should return a mismatch error. Here is the code I've tried so far.
Private Sub CommandButton1_Click()
Dim p As Integer, Tabl()
Redim Tabl(0)
For i = 0 To ListBox1.ListCount - 1
p = p + 1
Redim Preserve Tabl(p)
Tabl(p) = ListBox1.List(i)
Next i
For i = 0 To ListBox2.ListCount - 1
If IsNumeric(Application.Match(ListBox2.List(i), Tabl, 0)) Then
Msgbox"Correct"
End If
Next i
End Sub
Unfortunately, the program only calculates the first column repeatedly. How can I compare multiple columns?

Based on your description and a small evaluation of what your code does, you may be overthinking this. How about the following?
Private Sub CommandButton1_Click()
Dim myMsg As String
Dim byeMsg As String
myMsg = "Same name chosen."
byeMsg = "Those names don't match."
If ListBox1.Value = ListBox2.Value Then
MsgBox myMsg
Else
MsgBox byeMsg
End If
End Sub
Of course, instead of displaying a message using MsgBox, you could just as easily replace it with any code you need.

Related

Listbox.List(i) error - Method or Data Member not Found

I'm trying to use a multi-select listbox so users can select cleaning tasks they have completed and mark them as done. While looping through the list I want to see if the item is selected and create a record if so. When I try to use the .List method to return the data from a specific row, I keep getting the method not found error.
I originally did not have the forms 2.0 library loaded so I thought that was the issue, but that did not resolve the problem. I've also compacted and repaired thinking it might just be an odd fluke, but that did not help either.
'loop through values in listbox since its a multi-select
For i = 0 To listCleaningTasks.ListCount - 1
If listCleaningTasks.Selected(i) Then
'add entry to cleaning log
Set rsCleaning = CurrentDb.OpenRecordset("SELECT * FROM cleaning_log;")
With rsCleaning
.AddNew
.Fields("cleaning_task_id") = Form_frmCleaning.listCleaningTasks.List(i)
.Fields("employee_id") = Me.cmbUser
.Fields("cleanroom_id") = Me.cmbCleanroom
.Fields("cleaning_time") = Now()
.Update
.Close
End With
End If
Next i
Any ideas?
Use .listCleaningTasks.ItemData(r) to pull bound column value from row specified by index.
Use .listCleaningTasks.Column(c, r) to pull value specified by column and row indices.
Open and close recordset only one time, outside loop.
Really just need to loop through selected items, not the entire list.
Dim varItem As Variant
If Me.listCleaningTasks.ItemsSelected.Count <> 0 Then
Set rsCleaning = CurrentDb.OpenRecordset("SELECT * FROM cleaning_log")
With rsCleaning
For Each varItem In Me.listCleaningTasks.ItemsSelected
`your code to create record
...
.Fields("cleaning_task_ID") = Me.listCleaningTasks.ItemData(varItem)
...
Next
.Close
End With
Else
MsgBox "No items selected.", vbInformation
End If
Of course the solution of June7 is correct. If you need to store the selected items and then later recall and re-select the list box items, consider to get the selected items comma delimited using this function
Public Function GetSelectedItems(combo As ListBox) As String
Dim result As String, varItem As Variant
For Each varItem In combo.ItemsSelected
result = result & "," & combo.ItemData(varItem)
Next
GetSelectedItems = Mid(result, 2)
End Function
Store it into one column of a table and after reading it back pass it to this sub:
Public Sub CreateComboBoxSelections(combo As ListBox, selections As String)
Dim N As Integer, i As Integer
Dim selectionsArray() As String
selectionsArray = Split(selections, ",")
For i = LBound(selectionsArray) To UBound(selectionsArray)
With combo
For N = .ListCount - 1 To 0 Step -1
If .ItemData(N) = selectionsArray(i) Then
.Selected(N) = True
Exit For
End If
Next N
End With
Next i
End Sub
This will select items in your ListBox as they were before.

Problems with Null in VBA

I want the code to display the selection in ListBox1 in a MsgBox and "Select a Capacity" if ListBox1 is empty/not selected.
If I try to use IsEmpty(), then ListBox1.Value is Null.
If I use IsNull(), then ListBox1.Value is "".
Private Sub CommandButton3_Click()
Dim Cap As Integer
If IsNull(ListBox1) = True Then
MsgBox "Select a Capacity"
Exit Sub
End If
Cap = Left(ListBox1.Value, 2)
MsgBox Cap
End Sub
Any suggestions would be appreciated.
You could try:
If ListBox1.ItemsSelected.Count = 0 Then
MsgBox "Select a capacity"
Exit Sub
End If
Cap = Left(ListBox1.Value, 2)
The IsEmpty function is used to check is a variable of type Variant has been initialised. It cannot be used to check if a ListBox contains any entries.
The IsNull function checks if a variable has been set to Null. This doesn't help with checking a ListBox for entries.
Instead, use If ListBox1.ListCount = 0 Then to check if the ListBox is empty and use If ListBox1.ListIndex = -1 Then to check if any entries have been selected.
If the ListBox allows multiple selections at once then, as mentioned by #shoegazer100, use something like:
Dim rowNumber As Long
For rowNumber = 0 To (ListBox1.ListCount - 1)
If ListBox1.Selected(rowNumber) Then
' do something
End If
Next rowNumber
to determine which rows are currently selected (if Selected returns True for a particular row then the corresponding row in the ListBox is selected)

How to add multiple checkboxes in multiple columns (VBA)

I have a ListView with multiple columns. More precisely, the ListView contains 8 columns. 2 of them should be filled with checkboxes.
Currently only the first column contains checkboxes. It is defined as follows:
While Not rs.EOF
//first column with checkboxes
ListViewCustomer.ListItems.Add , , rs("Id")
ListViewCustomer.ListItems(ListViewCustomer.ListItems.Count).tag = rs("Status")
//second column etc.
ListViewCustomer.ListItems(ListViewCustomer.ListItems.Count).ListSubItems.Add , , rs("name")
....
//Here is the second column, which doesn't display the checkboxes
ListViewCustomer.ListItems(ListViewCustomer.ListItems.Count).ListSubItems.Add , , IIf(IsNull(rs("date_from")), "", rs("date_from"))
ListViewCustomer.ListItems(ListViewCustomer.ListItems.Count).tag = rs("Status2")
Wend
Do anyone have an idea how to add the checkboxes in the last column?
EDIT:
Is it possible to realize this column with adding via .Controls?
A ListView is a more expanded version of the ListBox control.
See ListBox control on msdn as well.
They both display records of rows (the ListView has more advanced formatting options). This however means that a record is a row. Therefore you select a row when you select one of the items.
The function of the checkbox is to allow the user to mark the row(s) that is the records(s) he selects.
Thus there is only one checkbox per row, at the front of the row.
Consider this code (this is Excel 2003 VBA, but gives you the idea):
Private Sub UserForm_Initialize()
Dim MyArray(6, 8)
'Array containing column values for ListBox.
ListBox1.ColumnCount = 8
ListBox1.MultiSelect = fmMultiSelectExtended
'Load integer values MyArray
For i = 0 To 5
MyArray(i, 0) = i
For j = 1 To 7
MyArray(i, j) = Rnd
Next j
Next i
'Load ListBox1
ListBox1.List() = MyArray
End Sub
You could do a custom ListBox or ListView if you really want. You could create a frame and put Labels and CheckBoxes on it. This is the only way to do this in Excel2003 where I tested. The ListBox object has no Controls child.
But this is more like a datagrid and not really a ListBox or ListView which by definition are a listing of records (rows).
Update:
I saw your update and that you really want to place the CheckBox at the end of the row.
If you only want one checkbox at the last row, you could do this custom checkbox. Again this is written for the ListBox, so need to convert it to your ListView if you want to.
Still requires a custom handling, but I had some time, so I did this code. See if you like it:
Private Sub ListBox1_Change()
For i = 0 To ListBox1.ListCount - 1
ListBox1.List(i, 3) = ChrW(&H2610)
Next i
ListBox1.List(ListBox1.ListIndex, 3) = ChrW(&H2611)
End Sub
Private Sub UserForm_Initialize()
Dim MyArray(5, 3)
'Array containing column values for ListBox.
ListBox1.ColumnCount = 4
ListBox1.MultiSelect = 0
ListBox1.ListStyle = 0
'Load integer values MyArray
For i = 0 To 5
MyArray(i, 0) = i
For j = 1 To 2
MyArray(i, j) = Rnd
Next j
MyArray(i, 3) = ChrW(&H2610)
Next i
'Load ListBox1
ListBox1.List() = MyArray
End Sub

VBA code multiple if condition and put complete datein respective column

I am creating macro and I am stuck in creating the main page of VBA code. we have a sheet named "Renewal" in which all the customer information we dump. Column C we have customer number, Column D We have product type Dental, LIFE & Dis. Column A we have to put complete data, and Column B we have to put annual premium. Now I want the main page where I can one input box1 in which I put customer number, combo box1 in which 3 option I will get "DENTAL, LIFE, DIS., input box2 Date of completion, and input box3 annual premium. If input box1 and combo box1 condition satisfy then date will put on same row of column A and annual premium in column B respectively.
The wording of your question was very interesting, maybe a screenshot might be better. Ok this is what I have crafted. I am sorry I am not sure this code will work 100% as I have not got Word installed on this machine so had to write it in notepad, so may not be the best solution. As suggested in one of the comments - you have to add add() in the button1_click event. Hopefully this has been of some use.
Private Sub add() 'Add the add sub routine to the button1_click
Sheets("Renewal").Activate() 'makes the sheet activate
if textbox1.text <> "" and textbox2.text <> "" and textbox3.text <> "" and combobox1.text <> "" then 'condition
dim pos as integer 'used to find next position
pos = findNext() 'adds next position value
activesheet.cells(1,pos).value = textbox2.text 'adds Date of completion
activesheet.cells(2,pos).value = textbox3.text 'adds annual premium
activesheet.cells(3,pos).value = textbox1.text 'adds customer number
activesheet.cells(4,pos).value = combobox1.text 'adds product type
'unsure if combobox1.text is correct.
end if 'end of the condition
End sub 'end of sub routine
Private function findNext() 'this function finds the next position in sheet
dim x as integer 'used as a counter
x = 1 'counter = 1
do 'start of iteration
x = x + 1 'counting
loop until activesheet.cells(1,x).value = "" 'end when cell (A, counter) has no value
return x 'returns the counter value
End function 'end of function
P.S. If you are a complete begin beginner - This video may help you with the ui: https://www.youtube.com/watch?v=hCIpMwdKCgE

Excel VBA: Searching for value in listbox based on value set in textbox

I am trying to write a code for a search button which searches a listbox based a specific input set in a textbox.
The values searched are always numbers, and the listbox contains values from a single column.
The code i wrote can be found below but i don't understand why it is not functional.
Legend:
SearchButton: A Button which upon clicking is supposed to initiate the search
SearchBox: The textbox which will contain the search value
AvailableNumberList: The listbox which contains the data
Thanks for your help :)
Private Sub SearchButton_Click()
Dim SearchCriteria, i, n As Double
SearchCriteria = Me.SearchBox.Value
n = AvailableNumberList.ListCount
For i = 0 To n - 1
If SearchCriteria = i Then
AvailableNumberList.ListIndex = i
End If
Next i
End Sub
Is this what you are trying?
'If SearchCriteria = i Then
If AvailableNumberList.List(i) = SearchCriteria Then
Also use Exit For once a match is found :)
Additional to #Siddharth Rout solution, this code allows to search in the ListBox even if the TextBox does not have the full word/number:
Private Sub SearchButton_Click()
Dim SearchCriteria, i, n As Double
SearchCriteria = Me.SearchBox.Value
n = AvailableNumberList.ListCount
For i = 0 To n - 1
If Left(AvailableNumberList.List(i),Len(SearchCriteria))=SearchCriteria Then
AvailableNumberList.ListIndex = i
Exit For
End If
Next i
End Sub
Thanks everyone for their code! =D