在vba中,从Query填充数组,然后将数据插入表中

时间:2017-07-12 06:51:39

标签: mysql arrays vba access-vba

所以我想将查询结果插入到数组中然后我将遍历数组以将新行插入到新表中。 这是我做过的代码:

Public cnn As New ADODB.Connection
Public db As DAO.Database

Public Sub SUD_Main()
    Set db = Access.Application.CurrentDb
    Set cnn = CurrentProject.Connection

     Refreash    
End Sub

Private Sub Refreash()
Dim DataArr() As String
    Dim p As Variant
    Dim sql As String
    Dim XDATA As New ADODB.Recordset
    Dim RDS As DAO.Recordset
    Set RDS = db.OpenRecordset("tbl_dets")

    sql = "SELECT DISTINCT NAME FROM Types_tbl WHERE NAME LIKE 'Rob%'"
    XDATA.Open sql, cnn, adOpenStatic

    '''
    '' HERE I WANT TO FILL DataArr FROM XDATA
    '''
    DataArr = XDATA.GetRows

    XDATA.Close
    For Each p In DataArr
        sql = "SELECT DISTINCT TID FROM Types_tbl WHERE NAME ='" & p & "'"
        XDATA .Open sql, cnn, adOpenStatic

       Do Until XDATA.EOF
       DoEvents 
           '''Inserting new records to tbl_dets
           RDS.AddNew
           RDS!Name = p
           RDS!TID= XDATA!TID
           RDS.Update
           XDATA.MoveNext
       Loop
       XDATA.Close
    Next
End Sub

那么我错过了什么?我的错误是在数组中,但不知道如何解决它。

1 个答案:

答案 0 :(得分:1)

您的代码大多数都是有效的,但您犯了一些错误。 GetRows返回带有rownumbers和字段的多维数组。因此,您无法将其融入字符串中。您需要使用变体类型的数组。

Private Sub Refreash()
    Dim DataArr() As Variant
    Dim p As Variant
    Dim sql As String
    Dim XDATA As New ADODB.Recordset
    Dim RDS As DAO.Recordset
    Set RDS = db.OpenRecordset("tbl_dets")

    sql = "SELECT DISTINCT NAME FROM Types_tbl WHERE NAME LIKE 'Rob%'"
    XDATA.Open sql, cnn, adOpenStatic

    '''
    '' HERE I WANT TO FILL DataArr FROM XDATA
    '''
    'Make sure XData fetches all records
    XData.MoveLast
    XData.MoveFirst
    DataArr = XDATA.GetRows

    XDATA.Close
    For Each p In PATTs
        sql = "SELECT DISTINCT TID FROM Types_tbl WHERE NAME ='" & p & "'"
        XDATA .Open sql, cnn, adOpenStatic

       Do Until XDATA.EOF
       DoEvents 
           '''Inserting new records to tbl_dets
           RDS.AddNew
           RDS!Name = p
           RDS!TID= XDATA!TID
           RDS.Update
           XDATA.MoveNext
       Loop
       XDATA.Close
    Next
End Sub

请注意,有一些事情我仍然不了解这个子,可能是因为它没有完成,例如它在设置它之后没有在任何地方使用DataArr以及使用ADO和DAO(I&#39 ; d在这种情况下只喜欢做DAO。)