Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

vba listobject CopyFromRecordset

Tags:

excel

vba

How to populate data from a recordset into a listobject? The code below is not completely working:

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
like image 312
ebelair Avatar asked Jun 24 '16 07:06

ebelair


People also ask

How to use CopyFromRecordset in VBA?

VBA CopyFromRecordset Range in Excel- Syntax Here is the syntax of the CopyFromRecordset method of range object. MaxRows are the maximum records to be copied, by default all records will be copied. MaxColumns are the maximum fields to be copied, by default all fields will be copied.

What is ListObject VBA?

VBA ListObject is a way of referring to the Excel tables while writing the VBA code. Using VBA LISTOBJECTS, we can create and delete tables and play around with Excel Tables in VBA code.


1 Answers

If you are always deleting the .DataBodyRange first, you can use the `.InsertRowRange'.

With Feuil3.ListObjects("TableArticles")
    If Not .DataBodyRange Is Nothing Then .DataBodyRange.Delete
    .InsertRowRange.CopyFromRecordset(oRS)
End With
like image 164
Gravitate Avatar answered Sep 23 '22 05:09

Gravitate