Run-Time error '91':
Object variable or With block variable not set
Help me to resolve this problem.
I don't know why this happened cause I just followed the instructions.
Sub QueryExcel(ByVal SQL_Statement As String)
On Error GoTo errHandle
Dim conn As ADODB.Connection
Dim rst As ADODB.Recordset
Dim sConnection As String, sSQL As String
Dim ws As Worksheet, i As Integer, iCheck As Integer
Dim num_records As Long
sConnection = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & ActiveWorkbook.FullName & _
";Extended Properties=""Excel 12.0;HDR=Yes;IMEX=0;ReadOnly=False"""
Set conn = CreateObject("ADOBD.Connection")
Set rst = CreateObject("ADOBD.Recordset")
sSQL = UCase(SQL_Statement)
conn.Open sConnection
If Left(sSQL, 6) = "UPDATE" Or InStr(sSQL, "INSERT INTO") > 0 Then
conn.Execute sSQL, num_records
MsgBox num_records & "records affected.", vbInformation
Else
rst.Open sSQL, conn, adOpenDynamic, adLockOptimistic
Set ws = Worksheets.Add
With ws
.Move ThisWorkbook.Worksheets(Sheets.Count)
'// Paste Record Set
.Range("A2").CopyFromRecordset rst
For i = 0 To rst.Fields.Count - 1
.Cells(1, i + 1) = rst.Fields(i).Name
Next i
End With
End If
Door:
If rst.State <> 0 Then rst.Close
If conn.State <> 0 Then conn.Close
Set rst = Nothing
Set conn = Nothing
Set ws = Nothing
Exit Sub
errHandle:
MsgBox "Error: " & Err.Description, vbInformation, "JJ Excel SQL.Application"
GoTo Door
End Sub
Code Above this text
this Code: If rst.State <> 0 Then
make all of this long code get error
Just a quick look at it, it's probably never loading the rst object properly.
Check your IF ELSE. Statement and I think you will find it never does this command
rst.Open sSQL, conn, adOpenDynamic, adLockOptimistic
You can check by putting a pause just before your error. And then in the intermediate window typing.
?typename(rst)
It it returns nothing you know where your issue is.
Set conn = CreateObject("ADOBD.Connection")
Set rst = CreateObject("ADOBD.Recordset")
In the above lines change ADOBD
to ADODB
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.