CopyFromRecordSet vs QuerrTables

J

Justin Dearing

I have a question of best practices. I needed to be able to insert the
results of a SQL query into an excel worksheet. I figured out 2 ways to
do this. The fisrt method is creating, refreshing, and deleting a
querytable. The second is to use copyfromrecordset. Both work equally
well from my perspective. However, I'm not sure which method is better.
I've included both functions I wrote. There class emember function and
both reference a private member ADODB.Connection object called cn.
Also, any memory or performance benifits to using querytable with
something besides an ADODB.Recordset object for the querytable?

Public Sub createQueryTable(ByRef sht As Worksheet, ByVal strSQL As
String)
Dim qt As QueryTable
Dim rs As Recordset

On Error Resume Next
cn.Execute "drop view qryTMRC"
cn.Execute "create view qryTMRC as " & strSQL
If Err.Number <> 0 Then
MsgBox Err.Description, vbCritical
End If
Set rs = cn.Execute(CommandText:="qryTMRC", Options:=adCmdTable)
Set qt = sht.QueryTables.Add(rs, sht.Application.ActiveCell)
qt.Refresh
qt.Delete
cn.Execute "drop view qryTMRC"
On Error GoTo 0
End Sub

Public Sub getQueryAsRange(ByRef sht As Worksheet, ByVal strSQL As
String)
Dim rs As Recordset

On Error Resume Next
cn.Execute "drop view qryTMRC"
cn.Execute "create view qryTMRC as " & strSQL
If Err.Number <> 0 Then
MsgBox Err.Description, vbCritical
End If
Set rs = cn.Execute(CommandText:="qryTMRC", Options:=adCmdTable)
sht.Application.ActiveCell.CopyFromRecordset rs
cn.Execute "drop view qryTMRC"
On Error GoTo 0
End Sub
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top