我有一个表名" product'和product_name,category作为字段。我想将product_name行值添加到重复类别值的组合框....
product_name | category
--------------+----------
Ceiling fan | fan
Table fan | fan
Wall fan | fan
我尝试以下代码,但没有做while语句它给出一个值,当我试图循环它时,机器挂起。 Plz帮助
Option explicit
Private sub cboCategories_Click()
cboProducts.clear
rs.open "select * from product". cn, adOpenDynamic. adLockOptimistic
With rs
.find "category=' " & cbiCategories.Text & " ' "
.moveFirst
With rs(0).value
Do until rs.EOF
cboProducts.AddItem rs(0).Value
rs.MoveNext
Loop
End with
End with
End sub
这是我目前的表。我想将product_name字段值输入到类别名称相同的组合框中,例如'粉丝'
答案 0 :(得分:0)
有几种方法可以给这种猫做皮肤。一种是从使用数据整形服务创建的断开连接的分层Recordset中获取ComboBox数据。
此示例假定带有标题行的CSV文件,但同样适用于Jet或其他数据库表:
Option Explicit
Private rsShapedProducts As ADODB.Recordset
Private Sub cboCategories_Click()
With cboProducts
.Clear
With rsShapedProducts
.MoveFirst
.Find "[Category]='" & cboCategories.List(cboCategories.ListIndex) & "'"
With ![Products].Value
.MoveFirst
Do Until .EOF
cboProducts.AddItem ![Product].Value
.MoveNext
Loop
End With
End With
.ListIndex = 0
End With
End Sub
Private Sub cboProducts_Click()
lblSelection.Caption = cboCategories.List(cboCategories.ListIndex) _
& " -> " _
& cboProducts.List(cboProducts.ListIndex)
End Sub
Private Sub Form_Load()
Set rsShapedProducts = New ADODB.Recordset
With rsShapedProducts
.CursorLocation = adUseClient
.Open "SHAPE {" _
& "SELECT [Category], [Product] FROM [products.txt] " _
& "ORDER BY [Category], [Product]" _
& "} AS [Products] COMPUTE [Products] BY [Category]", _
"Provider=MSDataShape;Data Provider=Microsoft.Jet.OLEDB.4.0;" _
& "Data Source='" & App.Path & "';Extended Properties='Text;Hdr=Yes'", _
adOpenStatic, _
adLockReadOnly, _
adCmdText
Set .ActiveConnection = Nothing
Do Until .EOF
cboCategories.AddItem ![Category].Value
.MoveNext
Loop
End With
Show
cboCategories.ListIndex = 0
End Sub
Private Sub Form_Unload(Cancel As Integer)
rsShapedProducts.Close
End Sub
我使用的测试数据:
Category,Product
Fan,Ceiling Fan
Fan,Table Fan
Fan,Wall Fan
Lamp,Floor Lamp
Lamp,Table lamp
Lamp,Desk Lamp
Table,Coffee Table
Table,End Table
Table,Kitchen Table
Table,Dining Table
Table,Card Table
答案 1 :(得分:0)
Private Function IsInCollection(ByVal Coll As Collection, CollKey As String) As Boolean
On Error GoTo errHandler
Dim b As Variant
b = Coll(CollKey)
IsInCollection = True
errHandler:
Err.Clear
Exit Function
End Function
Public Sub FillCombo()
Dim rs As Adodb.Recordset
Dim Coll As New Collection
Dim strNewValue As String
Set rs = fillMyRs
Do While Not rs.EOF
strNewValue = rs.Fields("category").Value
If IsInCollection(Coll, strNewValue) Then
strNewValue = strNewValue & " - " & rs.Fields("product_name").Value
Else
Coll.Add strNewValue, strNewValue
End If
Combo1.AddItem strNewValue
rs.MoveNext
Loop
End Sub