2011-04-17 57 views
2
  • 數據庫結構:

用戶名字符串幫助 - VBA - 搜索功能 - 數據庫MS接入

位置字符串

價格

  • 要求:

    我有一些項目列表框到它說100的用戶將在列表框中只選擇10個隨機(改變MULTISELECT到2fmMultiselect財產後)。我將有搜索按鈕。選擇並點擊搜索後,必須計算並顯示所選項目的總價格。

我的搜索代碼(感謝弗格森)

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 

該代碼只是爲了在一個文本框搜索和顯示。

現在,我需要將用戶從列表框中選擇的所有用戶名字段的價格總計。

+2

你爲什麼要在Access中使用ADO使用結果的陳述? DAO更有意義。但就此而言,我不清楚爲什麼你首先需要一個記錄集。你不想以總數的形式顯示結果嗎?在這種情況下,只需要將標準傳遞給用來打開表單的命令。 – 2011-04-18 02:11:26

回答

1

試試這個,但要確保列表框中的綁定列是你的表的ID字段。

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 

,你可以在你的SQL

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