If a listbox contains an item LIKE - vb.net

Is there anywhere to check whether a listbox contains an item which is similar to a string?
I have tried to use a Like statement but this doesn't work.
I have tried:
For i As Integer = 0 To TopicListBox.Items.Count - 1
If (TopicListBox.Items(i).ToString.Contains(Record.Item("Keyphrase2"))) Then
Dim Item As String = TopicListBox.Items(i).ToString
If Item Like "Questions related to:" & Record.Item("Keyphrase2") & ": |*| Qs" Then
Dim ItemSplit() As String = Item.Split(New Char() {"|"c})
Dim AmountOfQuestionsAfter As Integer = AmountOfQuestions + CInt(ItemSplit(1))
Item = ItemSplit(0) & AmountOfQuestionsAfter & ItemSplit(1)
Else
TopicListBox.Items.Add("Questions related to:" & Record.Item("Keyphrase2") & ": |" & AmountOfQuestions & "| Qs")
Exit For
End If
End If
Next

I don't really understand what you are trying to accomplish, but here is a LINQ function to return all the items that contain a certain string.
Dim lb As New ListBox
lb.Items.Add("asdf")
lb.Items.Add("asdfasdf")
lb.Items.Add("aifisasdf")
lb.Items.Add("adf")
'' find all items in the ListBox that contain the string "asdf"
Dim found = lb.Items.Cast(Of String).Where(Function(f) f.Contains("asdf"))
For Each s In found
'' do something with those items
Next

Can't you just do
If Item.Contains("Questions related to:" & Record.Item("Keyphrase2")) Then
...
End If
or
If Item.StartsWith("Questions related to:" & Record.Item("Keyphrase2")) Then
...
End If
?

Dim Found = (From Result In lb.Items Where Result.ToString = "Value" Select Result)
If (Found.Count > 0) Then
' your code
End If

Related

VBA: loop losing variable value

I've got a strange problem with a loop in VBA, as it seems to be losing the value of my variable. Any ideas why? If i delete the loop, debug.print shows "test", otherwise it's empty (unless I print the value of "dupa" inside the loop)... Seems very strange.
Function carbon_copy(indeks As String) As String
Dim emails(1 To 3) As String
Dim i As Integer
Dim dupa As String
emails(1) = "abc#wp.pl"
emails(2) = "pabc#wp.pl"
emails(3) = "rabc#wp.pl"
i = 1
dupa = "test"
Do While emails(i) <> ""
If i = indeks Then
GoTo NextIteration
End If
dupa = dupa & ";" & emails(i)
NextIteration:
i = i + 1
Loop
Debug.Print dupa
carbon_copy = dupa
End Function
You should get a runtime error 9 since you index i will be 4 after you looped through your emails String array. As soon as it tries to compare the value of emails(4) with "" it should produce the "index out of range" since you have defined your Array to be only 3 elements long.
For a little clarification try this example code, it should produce the same error:
Function littleTest()
Dim teststr(1 To 3) As String
Dim i As Integer
teststr(1) = "abc"
teststr(2) = "def"
teststr(3) = "ghi"
i = 1
Do While teststr(i) <> ""
Debug.Print "i do it for the " & i & " time!"
i = i + 1
Loop
End Function
You have already found the solution yourself since UBound() is returning the actual length of your array which is in your case three so it will never search beyond the array.
You're indexing out of the array bounds. The condition Do While emails(i) <> "" is always true given your array, so the this fails on emails(4). Just test the array bounds and loop over that:
For i = LBound(emails) To UBound(emails)
If emails(i) <> "" And i = indeks Then
dupa = dupa & ";" & emails(i)
End If
Next
Actually, I've already solved the problem by using other loop type (For i = 1 To UBound(emails), Next i), but why the previous loop did not work is still quite mysterious to me... If anyone can explain, I'd appreciate it, as I prefer to understand things rather thank just do them correctly.
W.
this should work (explanations in comments):
Function carbon_copy(indeks As Long) As String
Dim emails(1 To 3) As String
Dim i As Long
Dim dupa As String
emails(1) = "abc#wp.pl"
emails(2) = "pabc#wp.pl"
emails(3) = "rabc#wp.pl"
i = 1
Do While emails(i) <> ""
If i <> indeks Then dupa = dupa & ";" & emails(i) ' update 'dupa' if current index doesn't natch passed 'indeks'
i = i + 1
If i > UBound(emails, 1) Then Exit Do ' be sure to exit upon exceeding 'emails()' array size
Loop
carbon_copy = dupa
End Function

Insert number of record based on checkboxlist selected value in vb.net

I have this skill checkboxlist which contains skills that can be selected by the user. If the user select two skills,two records will be inserted to the table.
I tried this one:
Dim varSkillID As Integer()
varSkillID = split(skills, ",")
If varSkillID(0).value > 0 Then
Dim sql As String = Nothing
For I = 0 To varSkillID()
sql = "INSERT INTO tblConstituentSkills (skillID) VALUES ( " & varSkillID.Value & ")"
Next I
end if
but its not working. Thanks!
I also tried this code.
Dim varSkillID() As String = Split(skillID, ",")
For i As Integer = 0 To varSkillID.Length - 1
If varSkillID(i) <> "" Then
Using sql As New SqlProcedure("spInsertSkill")
sql.AddParameter("#ConstituentIdNo", constituentIdNo)
sql.AddParameter("#skillID", varSkillID(i))
sql.ExecuteNonQuery()
End Using
End If
Next i
It works when I only select single skill. But if I select two or more skills this error appears "Nullable object must have a value."
please use the editor help to design your request. It is very hard to read.
What does the errormessage say?
There is an End If missing
Where does constituentIdNo.Value is coming from?
To call the Sub:
Call r101("123456", "1,2,3,4")
the Sub:
Public Sub r101(ByVal constituentIdNo As String, ByVal skills As String)
Dim varSkillID() As String = Split(skills, ",")
Dim sql As String = Nothing
For i As Integer = 0 To varSkillID.Length - 1
If varSkillID(i) <> "" Then sql = "INSERT INTO tblConstituentSkills (ConstituentIdNo, skillID) VALUES (" & constituentIdNo & ", " & varSkillID(i) & ")"
Next i
End Sub
This is not the cleanest code, but the best I could create from your given feedback.
I don't see why to convert skills to integer.
I just read this and saved me.separate comma separated values and store in table in sql server
Thanks stackoverflow!you're a savior!

Access VBA How can I filter a recordset based on the selections in a multi select list box?

I am trying to use the OpenForm function to filter based on the selections in a multi select list box. what is the correct syntax for this, or is there a better way to go about it? For the sake of example let's say:
List Box has options Ken, Mike, and Sandy.
Car has options Car1, Car2, and Car 3. All cars are owned by 1 or more people from that list box.
If someone from the list box is selected, I would like to open a form containing the cars owned by those people selected.
Thank you!
Ok So I figured out a way to do it:
Create a string to hold a query
Use a For loop to populate the string based on each item selected
Put that string as a filter in the OpenForm command.
Here is the specific code I used to to it. My example in the original post used Cars and People, but my actual context is different: Estimators and Division of Work are the filters. Let me know if you have any questions about it if you're someone who has the same question! Since it might be confusing without knowing more about what exactly I'm trying to accomplish.
Dim strQuery As String
Dim varItem As Variant
'query filtering for estimators and division list box selections
strQuery = ""
If Me.EstimatorList.ItemsSelected.Count + Me.DivisionList.ItemsSelected.Count > 0 Then
For Each varItem In Me.EstimatorList.ItemsSelected
strQuery = strQuery + "[EstimatorID]=" & varItem + 1 & " OR "
Next varItem
If Me.EstimatorList.ItemsSelected.Count > 0 And Me.DivisionList.ItemsSelected.Count > 0 Then
strQuery = Left(strQuery, Len(strQuery) - 4)
strQuery = strQuery + " AND "
End If
For Each varItem In Me.DivisionList.ItemsSelected
strQuery = strQuery + "[DivisionID]=" & varItem + 1 & " OR "
Next varItem
strQuery = Left(strQuery, Len(strQuery) - 4)
End If
Using the JOIN function for cleaner and safer code
When you find yourself repeatedly building incremental SQL strings with delimiters like "," "AND" "OR" it is convenient to centralize the production of array data and then use the VBA Join(array, delimiter) function.
If the interesting keys are in an array, a user selection from a multiselect listbox to build a SQL WHERE fragment for the form filter property could look like this:
Private Sub lbYear_AfterUpdate()
Dim strFilter As String
Dim selction As Variant
selction = ListboxSelectionArray(lbYear, lbYear.BoundColumn)
If Not IsEmpty(selction) Then
strFilter = "[Year] IN (" & Join(selction, ",") & ")"
End If
Me.Filter = strFilter
If Not Me.FilterOn Then Me.FilterOn = True
End Sub
A generic function to pick any column data from selected lisbok rows may look like this:
'Returns array of single column data of selected listbox rows
'Column index 1..n
'If no items selected array will be vbEmpty
Function ListboxSelectionArray(lisbox As ListBox, Optional columnindex As Integer = 1) As Variant
With lisbox
If .ItemsSelected.Count > 0 Then
Dim str() As String: ReDim str(.ItemsSelected.Count - 1)
Dim j As Integer
For j = 0 To .ItemsSelected.Count - 1
str(j) = CStr(.Column(columnindex - 1, .ItemsSelected(j)))
Next
ListboxSelectionArray = str
Else
ListboxSelectionArray = vbEmpty
End If
End With
End Function
A few array builders in the application library and coding can be made look more VB.NET

Get text of listBox.selectedItems?

I have a listBox that displays members of a distribution group. I have the listbox setup for multisimple selection to select more than one member. I'm trying to do a loop to get the text of the selected items(index's). Here is my code which works fine for the first item. On the second item it crashes and says "Index was outside the bounds of the array." I will be taking these members and placing them in the To: field of a meeting request. So I need to to be formatted like this: member1;member2. I'm just using the MsgBox to test what I'm getting back. But I'm guessing I would need to add to an array. Please help!
For i = 0 To (myListBox.Items.Count - 1)
If myListBox.GetSelected(i) Then
MsgBox(myListBox.SelectedItems(i))
End If
Next
Re-read the question and I think you want to store this as a string. This should do what you are looking for:
Documentation on ListBox.Selected()
Dim MailStr as String
MailStr = ""
If myListBox.SelectedItems.Count = 0 Then
MsgBox "No User Selected"
Exit Sub
End If
For i = 0 to (myListBox.Items.Count - 1)
If myListBox.Selected(i) Then
MailStr = MailStr & myListBox.Items.Item(i) & "; "
End If
Next i
You can also try:
Dim assets As String
assets = ""
For Each item In assetListBox.SelectedItems
If assets = Nothing Then
assets = item
'Outputs 1 item "Member1"
MsgBox(assets)
Else
assets = assets & "; " & item
'Outputs 2 items in format "member1; member2"
MsgBox(assets)
End If
Next
This is what worked the way I want it.
Dim assets As String
assets = ""
For Each item In assetListBox.SelectedItems
If assets = Nothing Then
assets = item
'Outputs 1 item "Member1"
MsgBox(assets)
Else
assets = assets & "; " & item
'Outputs 2 items in format "member1; member2"
MsgBox(assets)
End If
Next

simple messagebox not getting displayed

i am trying to display a message box if the string is empty and this is the code i have tried.i am not getting any errors but still message box is not getting displayed.Any help is appreciated.
Dim tmp1 As String, tmp2 As String, tmp3 As String
Dim TextBox1 As String
Dim TextBox2 As String
Dim TextBox3 As String
tmp1 = Sheets("Sheet1").TextBox1.Value
If tmp1 = " " Then
MessageBox.Show ("file1 not selected")
End If
tmp2 = Sheets("Sheet1").TextBox2.Value
If tmp2 = " " Then
MessageBox.Show ("file2 not selected")
End If
tmp3 = Sheets("Sheet1").TextBox3.Value
If tmp3 = " " Then
MessageBox.Show ("file3 not selected")
Two things
A. If tmp2 = " " Then
If you are checking for blanks then use this
If Len(Trim(tmp2)) = 0 Then
B. MessageBox.Show is VB.Net. For VBA use
MsgBox "file1 not selected"
Similarly for others...
Based on your question, I recommend you try the following steps:
Name three cells in sheet 1 as TextBox1, 2, and 3 - use name manager in Excel (no VBA needed)
Type the below code in VBE:
code:
If Range("TextBox1").value = "" Then
Msgbox "pls fill field 1"
End if
I hope it makes sense and solves your problem.