2016-06-24 70 views
1

如何將數據從記錄集填充到listobject中? 下面的代碼是不完全工作:vba listobject CopyFromRecordset

oCN.ConnectionString = "DRIVER={SQL Server};Server=SRVSQL;Database=TEST;" 
oCN.Open 
Dim sqlString As String 
sqlString = "SELECT * FROM MYTABLE" 
oRS.Open sqlString, oCN 

With Feuil3.ListObjects("TableArticles") 
    If Not .DataBodyRange Is Nothing Then 
     .DataBodyRange.Delete 
    End If 

    ' This make a 91 error 
    Call .DataBodyRange.CopyFromRecordset(oRS) 
    ' This copy data into sheet, not into listobject 
    Call Feuil3.Range("A2").CopyFromRecordset(oRS) 
End With 

回答

1

最後我找到了解決方案。 只需調整列表對象的大小以適應內容:

With Feuil3.ListObjects("TableArticles") 
    If Not .DataBodyRange Is Nothing Then 
     .DataBodyRange.Delete 
    End If 

    Call .Range(2, 1).CopyFromRecordset(oRS) 
    Call .Resize(Feuil3.UsedRange) 
End With