“ Recordset”的工作方式因“ new”或“ CreateObject”而异

时间:2018-07-13 08:53:12

标签: sql excel vba excel-vba ado

在由[新ADODB.Recordset]创建的记录集上,[rs.RecordCount]不起作用。 但是它可以在由[CreateObject(“ ADODB.Recordset”)]制作的记录集上使用[rs.RecordCount]。

顺便说一句,它在[CreateObject(“ ADODB.Recordset”)]所创建的记录集上也不起作用[rs.fields([integer])]。 但是它可以在由[新ADODB.Recordset]创建的记录集的[rs.fields([integer])]上工作

如何在一个记录集上使用两个源([rs.fields([integer])]和[rs.RecordCount])?

Sub all_column()
    Call connectDB

    Dim strSql As String
    Dim Syntax As String
    Dim recordsAffected As Long
    Dim nameOfTable As String
    Dim numberOfRecord As Integer
    Dim i, next_i As Integer


    Set rsTable = CreateObject("ADODB.Recordset")
    rsTable.CursorLocation = adUseClient

    'This is query'
    strSql = "show tables"

    'Set recordset by [CreateObject("ADODB.Recordset")]'
    'just for return of [.RecordCount]'
    'Because of [.RecordCount] dose not work on [new ADODB.Recordset]'
    Set rs = CreateObject("ADODB.Recordset")
    rs.CursorLocation = adUseClient
    rs.Open strSql, cn, adOpenStatic
    numberOfRecord = rs.RecordCount
    rs.Close

    'Set recordset by [New ADODB.Recordset]'
    'because of [.Fields(0)] dose not work on [CreateObject("ADODB.Recordset")]'
    Set rs = New ADODB.Recordset
    rs.Open strSql, cn, adOpenStatic
    i = 2

    Do While rs.EOF = False
        nameOfTable = rs.Fields(0).Value
        strSql = "DESC " + nameOfTable + ";"
        rsTable.Open strSql, cn, adLockReadOnly

        next_i = i + rsTable.RecordCount

        Sheets("sheet1").Range("b" + CStr(i)).CopyFromRecordset rsTable
        Sheets("sheet1").Range("a" + CStr(i) + ":a" + CStr(next_i - 1)).Value = nameOfTable

        i = next_i

        rsTable.Close
        rs.MoveNext
    Loop

    rs.Close
    cn.Close
End Sub
  

ADO = Microsoft Active X数据对象6.1库

     

SQL = 5.7.14-google-log(Google)

     

EXCEL = Microsoft Excel 2016 MSO(16.0.10228.20080)

0 个答案:

没有答案