Public Function AddToCombo(ByVal strTable As String, _
                           ByVal strFields As String) As Collection
'第一个参数为表名,第二个为字段名
'第二个参数可写成fieldsname=fieldsname1+fieldsname2的形式
Dim rs As Recordset
Dim strSql As String
Dim coll As Collection
Dim i As Integer
strSql = "SELECT " + Space(1) + strFields + Space(1) + "FROM" + Space(1) + strTable
Set rs = gCon.Execute(strSql)
For i = 1 To rs.RecordCount--??为什么rs.recordcount的值总是-1???
    coll.Add rs.Fields(0).Value, i
Next
    Set AddToCombo = coll
    'Set coll = Nothing
End Function还有就是怎样将以加入collection中的项目取出来,存入一个变量中??thanks

解决方案 »

  1.   

    给你改写一下!
    Public Function AddToCombo(ByVal strTable As String, _
                               ByVal strFields As String) As Variant
    '第一个参数为表名,第二个为字段名
    '第二个参数可写成fieldsname=fieldsname1+fieldsname2的形式
    Dim rs As Recordset
    Dim strSql As String
    Dim coll() As string
    Dim i As Integer
    strSql = "SELECT " + Space(1) + strFields + Space(1) + "FROM" + Space(1) + strTable
    Set rs = gCon.Execute(strSql)
    For i = 1 To rs.RecordCount--??为什么rs.recordcount的值总是-1???
        ReDim Preserve(i-1)
        coll(i-1)= rs.Fields(0).Value, i
    Next
        Set AddToCombo = coll
        'Set coll = Nothing
    End Function为什么rs.recordcount的值总是-1???
    记录集里没有记录,看看是不是没找到数据!
      

  2.   

    Execute方法是异步执行的,可能根本就不会设置RecordCount来返回记录数,所以它的值就是-1解决方法就是不用For循环改成While循环即可
    while not rs.eof
     coll.Add rs.Fields(0).Value, i
    wend用coll.item(Index)取得Collection中的单个值 Index是元素在Collection中的索引,也可以用For Each枚举Collection中的所有记录
      

  3.   

    还忘了一点,在循环中应该增加一句 rs.movenext 否则永远只能取到第一个值,而且这个循环是一个死循环!while not rs.eof
     coll.Add rs.Fields(0).Value, i
     rs.movenext
    wend
      

  4.   

    谢谢!特别是CityBird(鹰扬九洲——只有想不到的,没有做不到的) 的:
    while not rs.eof
     coll.Add rs.Fields(0).Value, i
    wend