Lakshmi Narasimhan
Lakshmi Narasimhan

Reputation: 33

Help - VBA - Search Functionality - Database MS access

UserName String

Location String

Price Number

My search code ( Thanks to Alex sir)

enter code here
Private Sub CommandButton4_Click()

Dim Cn As ADODB.Connection
Dim rs As ADODB.Recordset
Dim sName As String

Set Cn = New ADODB.Connection
Cn.ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=d:\test2.accdb;Persist Security Info=False"
Cn.ConnectionTimeout = 40
Cn.Open

Set rs = New ADODB.Recordset

sName = Replace$(TextBox1.Text, "'", "''")
rs.Open "Select * from SampleTable where UserName = '" & sName & "'", Cn, adOpenForwardOnly, adLockReadOnly, adCmdText

If (rs.EOF) Then
    MsgBox "no match"
Else
    TextBox3.Text = rs("UserName") & " " & rs("Location")
     
    
    rs.Close
    
End If

Set rs = Nothing
Cn.Close
Set Cn = Nothing


End Sub

That code was just to search and display in a textbox.

Now, I need to total the price of what all UserName field selected by the user from listbox.

Upvotes: 2

Views: 1180

Answers (1)

Praesagus
Praesagus

Reputation: 2094

Try this, but make sure the bound column in your list box is the ID field of your table.

Private Function SelectedListString(lstSelected As Access.ListBox) As String
'Loop though a list and get the IDs of all the selected items
'Assumes the bound column is the contains the ID field
    Dim sList As String
    Dim vSelected As Variant        
    With lstSelected
        For Each vSelected In .ItemsSelected
            sList = sList & .ItemData(vSelected) & ","
        Next
    End With
    If sList <> "" Then sList = Left(sList, Len(sList) - 1) 'trim trailing coma
    SelectedListString = sList
End Function

you can use the result in an IN statement in your SQL

Dim sSql As String
If myListbox.ItemsSelected.Count > 0 Then
    sSql = "SELECT * FROM table WHERE IDField IN (" & SelectedListString(myListbox) & ")"
End If

Upvotes: 1

Related Questions