J
Jim Hughes
In Excel VBA code, Runquery works, but Runquery2 does not.
Runquery2 gives a "Application-defined or object-defined error" on the Set
oQuery line
I would rather use the Runquery2 syntax as it is much shorter!
Any ideas why it is failing?
Public Sub runquery()
' required Tools | Reference to Microsoft Activex Data Objects Library
On Error GoTo e
Dim oQuery As QueryTable
Dim connstring As String
connstring = "Provider=sqloledb;Data Source=htivm;Initial
Catalog=pubs;Integrated Security=SSPI;"
Dim sql As String
sql = "SELECT * FROM AUTHORS"
Dim conn As ADODB.Connection
Dim rs As ADODB.Recordset
Set conn = New ADODB.Connection
conn.ConnectionString = connstring
conn.Open
Set rs = New ADODB.Recordset
rs.CursorLocation = adUseClient
rs.Open sql, conn, adOpenDynamic, adLockReadOnly
Set oQuery = Sheet1.QueryTables.Add(rs, Sheet1.Range("A1"))
oQuery.Refresh
rs.Close
conn.Close
Exit Sub
e:
Debug.Print Err.Description
End Sub
Public Sub runquery2()
On Error GoTo e
Dim oQuery As QueryTable
Dim connstring As String
connstring = "Provider=sqloledb;Data Source=htivm;Initial
Catalog=pubs;Integrated Security=SSPI;"
Dim sql As String
sql = "SELECT * FROM AUTHORS"
Set oQuery = Sheet1.QueryTables.Add(connstring, Sheet1.Range("A1"), sql)
oQuery.Refresh
Exit Sub
e:
Debug.Print Err.Description
End Sub
Runquery2 gives a "Application-defined or object-defined error" on the Set
oQuery line
I would rather use the Runquery2 syntax as it is much shorter!
Any ideas why it is failing?
Public Sub runquery()
' required Tools | Reference to Microsoft Activex Data Objects Library
On Error GoTo e
Dim oQuery As QueryTable
Dim connstring As String
connstring = "Provider=sqloledb;Data Source=htivm;Initial
Catalog=pubs;Integrated Security=SSPI;"
Dim sql As String
sql = "SELECT * FROM AUTHORS"
Dim conn As ADODB.Connection
Dim rs As ADODB.Recordset
Set conn = New ADODB.Connection
conn.ConnectionString = connstring
conn.Open
Set rs = New ADODB.Recordset
rs.CursorLocation = adUseClient
rs.Open sql, conn, adOpenDynamic, adLockReadOnly
Set oQuery = Sheet1.QueryTables.Add(rs, Sheet1.Range("A1"))
oQuery.Refresh
rs.Close
conn.Close
Exit Sub
e:
Debug.Print Err.Description
End Sub
Public Sub runquery2()
On Error GoTo e
Dim oQuery As QueryTable
Dim connstring As String
connstring = "Provider=sqloledb;Data Source=htivm;Initial
Catalog=pubs;Integrated Security=SSPI;"
Dim sql As String
sql = "SELECT * FROM AUTHORS"
Set oQuery = Sheet1.QueryTables.Add(connstring, Sheet1.Range("A1"), sql)
oQuery.Refresh
Exit Sub
e:
Debug.Print Err.Description
End Sub