循环记录集的问题,试图找到数据和数据库记录之间的匹配

时间:2015-01-13 11:16:33

标签: vba excel-vba access-vba excel

我对SQL和整个ADO环境都很陌生。我要做的是查看字符串是否已经存在于ID表中。当我使用range.copyfromrecordset方法时,结果显示正常。 但是当我遍历代码时,我无法以某种方式在字段和行中找到字符串。

使用recordset.recordcount时,它给出-1。字符串“SWED-A.ST”在我正在访问和检索的ID表中,但是如何循环记录集并使用debug.print在即时窗口中显示它?我试图通过使用循环和movenext循环遍历字段,但只显示表标题“ID”....

代码

Sub Macro1() ' Tester Sub

    Dim TickerID As String: TickerID = "SWED-A.ST"
    Dim SQLString As String: SQLString = "SELECT TOP 1 ID FROM Instruments WHERE ID = '" & TickerID & "'"

    Dim ADODBBuilder As ADODBBuilder: Set ADODBBuilder = New ADODBBuilder
    Dim RecordSet As ADODB.RecordSet: Set RecordSet = ADODBBuilder.ReturnRecordset(TickerID, , , SQLString)

Public Function ReturnRecordset(Optional TickerID As String, Optional startdate As Date, Optional enddate As Date, Optional CustomSQLString As String) As ADODB.RecordSet

Const ConnectionPath As String = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users\name\Desktop\DataBase.accdb;Persist Security Info=False;"

    Dim DataConnection As ADODB.Connection: Set DataConnection = New ADODB.Connection
    Dim RecordSet As ADODB.RecordSet: Set RecordSet = New ADODB.RecordSet

    DataConnection.ConnectionString = ConnectionPath
    DataConnection.Open

    If Len(CustomSQLString) > 0 Then
        SQLString = CustomSQLString
    Else
         If Sheets("Mainwindow").Btn_CurrentTime.Value = True Then
            SQLString = "SELECT * FROM " & TickerID _
            & " WHERE [Date] BETWEEN #" & startdate & "# AND #" & enddate & "#"
        Else
            SQLString = "SELECT * FROM " & TickerID
        End If
    End If

    With RecordSet
        .ActiveConnection = DataConnection
        .Source = SQLString
        .LockType = adLockReadOnly
        .CursorType = adOpenForwardOnly
        .Open
    End With

    Set ReturnRecordset = RecordSet

    'Cleanup
    Set RecordSet = Nothing
    Set DataConnection = Nothing

End Function

1 个答案:

答案 0 :(得分:1)

默认ADO .Open使用adOpenForwardOnly游标,该游标始终返回-1的.RecordCount。您还在记录集属性中指定adOpenForwardOnly。您需要将其更改为adOpenStaticadOpenKeyset才能获得准确的记录计数。

DataConnection.Open, adOpenStatic
 ···
With RecordSet
    .ActiveConnection = DataConnection
    .Source = SQLString
    .LockType = adLockReadOnly
    .CursorType = adOpenStatic
    .Open
End With