CurrentProject.Connection.Execute(strSQL) immediately produces failed connection error

I have created a SQL statement using code that I want to run using Set 'variable' = currentproject.connection.execute(strSQL).

In case, I immediately receive the error "run-time error '-2147467259 (800004005)': Method 'Execute of object '_connection' failed.

A similar line of code works in this module fine and if I cut and paste the strSQL statement from the debug window to a query, the query runs fine.  

I'm a little lost as to what I might need to is the code.  The line that produces the error is near the bottom and marked.  Any insights would be greatly appreciated.


Private Sub cmdPunch1_Click()

Dim intSubID, intCoderID, intRecordCount, intKeyCount As Integer
Dim strTable, strList, strWhere, strSQLcheck, strSQLKey As String

Dim varItems(), varCheckKeys(), varKey(), varCheckData() As Variant
Dim rstCheckKeys, rsttest, rstCheckData, rstAddKeys As ADODB.Recordset

    intSubID = Me!lstSubID.Column(0)
    intCoderID = Me!lstCoderID.Column(0)
    strTable = "ftbl" & Me!lstFirst.Column(0)
    strForm = "ffrm" & Me!lstFirst.Column(0)
'Debug.Print intSubID, intCoderID, strTable
'Step 1: determine if ID is the only primary key

  strSQLKey = "SELECT tblPrimaryKeyNames.KeyName" & vbCrLf
  strSQLKey = strSQLKey & "        FROM tblPrimaryKeyNames" & vbCrLf
  strSQLKey = strSQLKey & "       WHERE (((tblPrimaryKeyNames.TableName)=" & """" & strTable & """" & "))" & vbCrLf
  strSQLKey = strSQLKey & "    GROUP BY tblPrimaryKeyNames.KeyName" & vbCrLf
  strSQLKey = strSQLKey & "      HAVING (((tblPrimaryKeyNames.KeyName)<>""ID""));"

  Debug.Print strSQLKey
  Set rstAddKeys = CurrentProject.Connection.Execute(strSQLKey)

  varCheckKeys() = rstAddKeys.GetRows
  intRecordCount = UBound(varCheckKeys, 2)
  If intRecordCount > 0 Then
        'Step 2: If more than one primary key, then use inputbox to get values for them
                'add key names to array
        ReDim varKey(0, intRecordCount)
        For a = 0 To intRecordCount
            varKey(0, a) = inputbox(varCheckKeys(0, a), "Enter the value for:")
        'SELECT ftblDataEntryTest.ID, ftblDataEntryTest.Relative, ftblDataEntryTest.Battery
        'FROM ftblDataEntryTest
        'WHERE (((ftblDataEntryTest.ID)=1) AND ((ftblDataEntryTest.Relative)="uncle")
        'AND ((ftblDataEntryTest.Battery)="first"));

        strList = strTable & ".ID, "
        strWhere = strTable & ".ID)=" & intSubID & ") AND (("
        For x = 0 To intRecordCount
            If IsNull(varCheckKeys(0, x)) = False Then
                strList = strList & strTable & "." & varCheckKeys(0, x) & ", "
                strWhere = strWhere & strTable & "." & varCheckKeys(0, x) & ")= " & varKey(0, x) & ") AND (("
            End If
        strList = Left$(strList, Len(strList) - 2)
        strWhere = Left$(strWhere, Len(strWhere) - 7)
        strList = strTable & ".ID"
        strWhere = strTable & ".ID)=" & intSubID & ")"
  End If

'Step 3: Create StrSQL based on strList and strWhere key values

        strSQLcheck = "SELECT " & strList & " FROM " & strTable & vbCrLf
        strSQLcheck = strSQLcheck & "  WHERE ((" & strWhere & ";"
        Debug.Print strSQLcheck

'Step 4: Determine if a record for these key values already exists

------------ ERROR PRODUCED HERE ---------  
    Set rstCheckData = CurrentProject.Connection.Execute(strSQLcheck)
-------------ERROR PRODUCED HERE----------

    If rstCheckData.RecordCount > 1 Then
        MsgBox "Data for this subject already exists in this table.  Go to the Edit Data area instead"

'Step 5: If new, then open form and pass values
        varItems = adhPutItem(varItems, "SubID", intSubID)
        varItems = adhPutItem(varItems, "CoderID", intCoderID)
        DoCmd.OpenForm strForm, , , , , , OpenArgs:=varItems
    End If

End Sub
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

It's a bit complex, but it looks to me like you miss some closing right parenthesis for one of the possible outcomes of building StrWhere.

try running it to Immediate window and inspect the strSQLcheck instead of executing.
do not use vbCrlf in your SQL strings

  strSQLKey = "SELECT tblPrimaryKeyNames.KeyName"
  strSQLKey = strSQLKey & " FROM tblPrimaryKeyNames" &
  strSQLKey = strSQLKey & " WHERE (((tblPrimaryKeyNames.TableName)=" & """" & strTable & """" & "))"
  strSQLKey = strSQLKey & " GROUP BY tblPrimaryKeyNames.KeyName"
  strSQLKey = strSQLKey & " HAVING (((tblPrimaryKeyNames.KeyName)<>""ID""));"


Dim intSubID, intCoderID, intRecordCount, intKeyCount As Integer

only intKeyCount get created as an integer all others will be variants, the same with your other declaration lines. In vba you need to declare the data type of each variable individually or else they will default to variant.

pansophyAuthor Commented:

This is the SQL statement copied directly from the immediate window (produced using the debug.print command)

SELECT ftblDataEntryTest.ID, ftblDataEntryTest.Battery, ftblDataEntryTest.Relative
FROM ftblDataEntryTest
WHERE (((ftblDataEntryTest.ID)=1) AND ((ftblDataEntryTest.Battery)=1) AND ((ftblDataEntryTest.Relative)="uncle"));

The statement runs when I copy it into a SQL query window.  

Could the module be corrupted??
Active Protection takes the fight to cryptojacking

While there were several headline-grabbing ransomware attacks during in 2017, another big threat started appearing at the same time that didn’t get the same coverage – illicit cryptomining.

I aggree with Steve on the Dim. And it could be the source of problem here, - try making an explicit declaration like:

Dim rstCheckKeys As ADODB.Recordset, rsttest As ADODB.Recordset, rstCheckData As ADODB.Recordset, rstAddKeys As ADODB.Recordset

I also agree with Steve in principle on the vbCrLf, - but in this case I shouldn't think it would make any difference since it comes in front of keywords (don't do it in SQL Server pass-through though!).

pansophyAuthor Commented:
I changed my declarations to:

Dim rstCheckKeys As ADODB.Recordset
Dim rsttest As ADODB.Recordset
Dim rstCheckData As ADODB.Recordset
Dim rstAddKeys As ADODB.Recordset

and removed the vbCrLf from all my SQL statements.  Sadly, I receive the same error.  

Another odd piece of information.  In this code I make two different SQL strings.  If I simply change

Set rstAddKeys = CurrentProject.Connection.Execute(strSQLCheck)


Set rstAddKeys = CurrentProject.Connection.Execute(strSQLKey)

Using the second SQL statement works just fine.  What about a SQL statement coudl cause the connection to fail??  

As I said, I copied the SQL string directly from the immediate window to a query and it ran perfectly.  So, I'm not even sure what could be wrong with a SQL that would allow it to run directly from a query window but cause a connection error in a module.

Thanks for any insights.
Try changing the two SQL Calls to:

rstAddKeys.Execute(strSQLKet), CurrentProject.Connection, adOpenDynamic, adLockOptimistic

rstAddKeys.Execute(strSQLCheck), CurrentProject.Connection, adOpenDynamic, adLockOptimistic
Just to be on the safe side: are you up to date with SP's ?


And then I forgot, you might try closing rstAddKeys in between SQL calls:

set rstAddKeys =Nothing

Sorry, - i confused your code with another case, - disregard previous msg:
rstAddKeys.Execute(strSQLKey), CurrentProject.Connection, adOpenDynamic, adLockOptimistic
rstAddKeys.Execute(strSQLCheck), CurrentProject.Connection, adOpenDynamic, adLockOptimistic

pansophyAuthor Commented:
rstAddKeys.Execute isn't a command, or at least it didn't let me run it as such.  I tried with your suggestion and I got the same connection error.  

I'm really beginning to think the db is just corrupted...
pansophyAuthor Commented:
Okay, lets up this to 200 points.

I exported the three tables I needed for this code to a text file and copied the module to a text file as well to eliminate any corrupted elements from the data/code.

I imported the tables form the text files and copied the code into a module in a new database.  I got the same connection error.  

Better still, I simplified the code to this and still got the error:

Private Sub strProblem()

Dim strSQL As String
Dim rstCheckKeys As ADODB.Recordset

    strSQL = "SELECT ftblDataEntryTest.ID, ftblDataEntryTest.Battery, ftblDataEntryTest.Relative FROM ftblDataEntryTest WHERE (((ftblDataEntryTest.ID)=1) AND ((ftblDataEntryTest.Battery)=4) AND ((ftblDataEntryTest.Relative)=""uncle""));"
Set rstCheckData = CurrentProject.Connection.Execute(strSQL)
End Sub

If I copy the Select statement into a query it retrieves records just as it should.  I am truly befuddled.

Thanks for keeping the suggestions coming.
pansophyAuthor Commented:
Well I found the solution.

Apparently, using the field name "relative" caused the problem.  Removing the field eliminated the error, so I changed the field name to 'family' and the code runs as it should.  

pansophyAuthor Commented:
svenkarlsen> Is there any way for me to give you the points for effort without misleading those scanning for help by accepting an incorrect solution as correct??  
that's just one of those things ;-)

You're very kind, but as I did not provide a solution, I suggest you make a posting for point refund and question removal (please see the help for instructions).

Kind Regards,
jadedataMS Access Systems CreatorCommented:
No comment has been added lately, so it's time to clean up this TA.
I will leave the following recommendation for this question in the Cleanup topic area:

PAQ - no points refunded

Please leave any comments here within the next seven days.

EE Cleanup Volunteer
PAQed - no points refunded (of 200)

EE Moderator

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
Microsoft Access

From novice to tech pro — start learning today.