VBA SQL query strings, how much is supported? - sql

still working on a query for a project and my partner has managed to come up with a nifty SQL statement what works wonders when run but wont seem to work in VBA and it has got me questioning how much of SQL statements are supported in VBA
This is the original query which my work partner whipped up and it works great when running the query in SQL
SELECT
crm_clients.`id`,
crm_clients.`national_insurance`,
crm_clients.`total_hmrc`,
(SELECT
crm_crmuseractions.title
FROM
dev_pfands.`crm_crmuseractions`
WHERE crm_crmuseractions.`id` = crm_clients.`status`) AS `status`
FROM
dev_pfands.`crm_clients`
INNER JOIN crm_client_cheques
ON crm_clients.id = crm_client_cheques.`client_id`
INNER JOIN dev_pfands.`crm_payments`
ON crm_clients.id = crm_payments.`client_id`
INNER JOIN dev_pfands.`crm_self_assesments`
ON crm_clients.id = crm_self_assesments.`client_id`
WHERE crm_clients.`status` = 9
OR crm_clients.`status` = 8
OR crm_clients.`status` = 7
OR crm_clients.`national_insurance` != ''
OR crm_clients.`id` != ''
I know VBA likes the SQL structured a little different so i adapted it to this, which maybe wrong so if it is feel free to burn me on it because i need to learn.
sql = "SELECT crm_clients.id, crm_clients.national_insurance, crm_clients.total_hmrc _
(SELECT _
crm_crmuseractions.title _
FROM _
crm_crmuseractions _
WHERE crm_crmuseractions.id = crm_clients.status ) AS 'status _
FROM _
crm_clients _
INNER JOIN crm_client_cheques _
ON crm_clients.id = crm_client_cheques.client_id _
INNER JOIN crm_payments _
ON crm_clients.id = crm_payments.client_id _
INNER JOIN crm_self_assesments.client_id _
WHERE crm_clients.status = 9 _
OR crm_clients.status = 8 _
OR crm_clients.status = 7 _
OR crm_clients.national_insurance != '' _
OR crm_clients.id != '' "
Apologies in advance if its something ive missed but anything other than simple selects or inserts/deletes and updates some of the other features of SQL like joins etc dont seem to work for me in VBA
If anyone knows where i've gone wrong then that'll be great and if ive done it fine and its non supported features even an explanation of why would be great so i can related it back to my work friends who believes it works.
Thanks in advanced guys.

Dim query As String
query = "SELECT " & _
"crm_clients.id, " & _
"crm_clients.national_insurance, " & _
"crm_clients.total_hmrc, " & _
"(SELECT " & _
" crm_crmuseractions.Title " & _
"FROM " & _
" dev_pfands.crm_crmuseractions " & _
"WHERE crm_crmuseractions.`id` = crm_clients.status) AS 'status' " & _
"FROM " & _
"dev_pfands.crm_clients " & _
"INNER JOIN crm_client_cheques " & _
" ON crm_clients.id = crm_client_cheques.client_id " & _
"INNER JOIN dev_pfands.crm_payments " & _
" ON crm_clients.id = crm_payments.client_id " & _
"INNER JOIN dev_pfands.crm_self_assesments " & _
" ON crm_clients.id = crm_self_assesments.client_id " & _
"WHERE crm_clients.status = 9 " & _
"OR crm_clients.status = 8 " & _
"OR crm_clients.status = 7 " & _
"OR crm_clients.national_insurance != '' " & _
"OR crm_clients.id != ''"

You need to concatenate the strings of data across the multiple lines like so:
strText = "This is the first line " & _
"This is the second line"
Given the large amount of text you have, you may run into an error Too many line continuations (as the maximum amount of line continuations is 25). In which case you can concatenate the strings like so:
strText = "This is the first line"
strText = strText & "This is the second line"
Note
As you are writing a SQL statement, you need to make sure that you include spaces in the correct places i.e. you most likely need to leave a space at the end of each line.

write it without single ticks and avoid single quotes, in VBA use double quotes, always.
something like this
Sql = "SELECT" & _
" crm_clients.""id""," & _
" crm_clients.""national_insurance"","

Related

Query holds on to old criteria & Subform won't refresh

I'm currently working on redesigning my company's access database from scratch, with no prior experience, because the last edits to its structure were made in 2006, and it's basically a list with 200k records that's slow ass hell. (current tests with working features are already showing significant improvements, yay!)
I tried to create a subform that displays the result of a query, but the query itself depends on a multiselect. The query acts on a customer Id and returns results based on the selected customers. (this works)
I've been looking and searching for a solution, but, i just can't figure out what to do.
The problem i'm dealing with is twofold, and i suspect related, but first a little bit of context.
First of all, the subform just refuses to update visually. While the query holds the desired results, the subform doesn't update at all, i've tried refresh, docmd.requery, you name it, the only thing that works is basically 'reattaching' the source. Any manner that managed to refresh the shown results are not accessible from the 'surface'.
Second, the query seems to 'hold on' to whatever clients were previously selected. Even though it can go from all clients (i have written this as a 'no selection means everything') to specific clients, in between selections, it keeps the criteria from the previous selection, and brings them forward.
'Dashboard' is the form in which the subform TabGeneralSubform is nested , qryTetraGeneral is the query used as a source for the subform. MultiCustomer is the multiselect form.
Sub ListAll_Click() [access vba]
Set MyDB = CurrentDb
flgSelectAll = 0
Set qdef = MyDB.QueryDefs("qryTetraGeneral")
'strSQL is based on the SQL conversion of the SelectClientAll query
'the final AND clause will be appended by strWhere which is based on the MultiList Selection
'If there is no selection the query will default to All active Subs
strSQL = "SELECT [EQ-TETRA_ISSI].ISSI,[EQ-TETRA_TEI].TEI, [EQ-TETRA_ISSI].Active," & _
" [EQ-TETRA_TEI].Activation, Client_Table.[Customer Name], Client_Table.[Customer ID], [EQ-TETRA_REQFUL].ReqType, SERVICEREQUEST_TABLE.REQNUM," & _
" SERVICEREQUEST_TABLE.REQDATE, SERVICEREQUEST_TABLE.RESPUSER" & _
" FROM ((Client_Table INNER JOIN [EQ-TETRA_ISSI] ON Client_Table.[External Customer Index] = [EQ-TETRA_ISSI].[Customer Index])" & _
" INNER JOIN SERVICEREQUEST_TABLE ON Client_Table.[External Customer Index] = SERVICEREQUEST_TABLE.Index) INNER JOIN ([EQ-TETRA_TEI]" & _
" INNER JOIN [EQ-TETRA_REQFUL] ON [EQ-TETRA_TEI].TEI = [EQ-TETRA_REQFUL].TEI) ON (SERVICEREQUEST_TABLE.REQNUM = [EQ-TETRA_REQFUL].Reqnum)" & _
" AND ([EQ-TETRA_ISSI].ISSI = [EQ-TETRA_REQFUL].ISSI)" & _
" WHERE ((([EQ-TETRA_TEI].TEI)=[EQ-TETRA_REQFUL].[TEI]) AND (([EQ-TETRA_ISSI].Active)=True) AND (([EQ-TETRA_TEI].Activation)=True) AND ("
'extracts selection from list and creates SQL line to be added to strSQL
For i = 0 To MultiCustomer.ListCount - 1
If MultiCustomer.Selected(i) Then
flgSelectAll = flgSelectAll + 1
strIN = strIN & "([EQ-TETRA_ISSI].[Customer Index]=" & MultiCustomer.Column(0, i) & ")" & " OR "
End If
Next
If flgSelectAll = 0 Then
strSQL = "SELECT [EQ-TETRA_ISSI].ISSI,[EQ-TETRA_TEI].TEI, [EQ-TETRA_ISSI].Active," & _
" [EQ-TETRA_TEI].Activation, Client_Table.[Customer Name], Client_Table.[Customer ID], [EQ-TETRA_REQFUL].ReqType, SERVICEREQUEST_TABLE.REQNUM," & _
" SERVICEREQUEST_TABLE.REQDATE, SERVICEREQUEST_TABLE.RESPUSER" & _
" FROM ((Client_Table INNER JOIN [EQ-TETRA_ISSI] ON Client_Table.[External Customer Index] = [EQ-TETRA_ISSI].[Customer Index])" & _
" INNER JOIN SERVICEREQUEST_TABLE ON Client_Table.[External Customer Index] = SERVICEREQUEST_TABLE.Index) INNER JOIN ([EQ-TETRA_TEI]" & _
" INNER JOIN [EQ-TETRA_REQFUL] ON [EQ-TETRA_TEI].TEI = [EQ-TETRA_REQFUL].TEI) ON (SERVICEREQUEST_TABLE.REQNUM = [EQ-TETRA_REQFUL].Reqnum)" & _
" AND ([EQ-TETRA_ISSI].ISSI = [EQ-TETRA_REQFUL].ISSI)" & _
" WHERE ((([EQ-TETRA_TEI].TEI)=[EQ-TETRA_REQFUL].[TEI]) AND (([EQ-TETRA_ISSI].Active)=True) AND (([EQ-TETRA_TEI].Activation)=True)) ORDER BY [EQ-TETRA_ISSI].ISSI;"
Else
strWhere = Left(strIN, Len(strIN) - 3) & ")) ORDER BY [EQ-TETRA_ISSI].ISSI;"
strSQL = strSQL + strWhere
End If
qdef.SQL = strSQL
Call CallRefreshForm([Forms]![Dashboard])
For Each ListObject In MultiCustomer.ItemsSelected
MultiCustomer.Selected(ListObject) = False
Next ListObject
Now, admittedly, the code is a bit cobbled together from what my predecessors left behind, and the SQL statement looks like a mess, however, it works and displays the desired results based on the criteria, which currently, is good enough for me. I'll probably try trimming it down later when i know all desired features are working.
There are several ways that this can be streamlined. Firstly when you build the SQL based on the list box, rather than use a lot of IN/OR, just use IN once (I'm air-coding a bit here, so forgive any slight errors)
For i = 0 To MultiCustomer.ListCount - 1
If MultiCustomer.Selected(i) Then
strSQL = strSQL & MultiCustomer.Column(0, i) & ","
End If
Next i
If Right(strSQL,1)="," Then strSQL=Left(strSQL,Len(strSQL)-1)
If Len(strSQL)>0 Then
strSQL="SELECT [EQ-TETRA_ISSI].ISSI,[EQ-TETRA_TEI].TEI, [EQ-TETRA_ISSI].Active," & _
" [EQ-TETRA_TEI].Activation, Client_Table.[Customer Name], Client_Table.[Customer ID], [EQ-TETRA_REQFUL].ReqType, SERVICEREQUEST_TABLE.REQNUM," & _
" SERVICEREQUEST_TABLE.REQDATE, SERVICEREQUEST_TABLE.RESPUSER" & _
" FROM ((Client_Table INNER JOIN [EQ-TETRA_ISSI] ON Client_Table.[External Customer Index] = [EQ-TETRA_ISSI].[Customer Index])" & _
" INNER JOIN SERVICEREQUEST_TABLE ON Client_Table.[External Customer Index] = SERVICEREQUEST_TABLE.Index) INNER JOIN ([EQ-TETRA_TEI]" & _
" INNER JOIN [EQ-TETRA_REQFUL] ON [EQ-TETRA_TEI].TEI = [EQ-TETRA_REQFUL].TEI) ON (SERVICEREQUEST_TABLE.REQNUM = [EQ-TETRA_REQFUL].Reqnum)" & _
" AND ([EQ-TETRA_ISSI].ISSI = [EQ-TETRA_REQFUL].ISSI)" & _
" WHERE [EQ-TETRA_TEI].TEI=[EQ-TETRA_REQFUL].[TEI] " _
& " AND [EQ-TETRA_ISSI].Active=True " _
& " AND [EQ-TETRA_TEI].Activation=True " _
& " AND [EQ-TETRA_ISSI].[Customer Index] IN (" & strSQL & ")
Else
strSQL="SELECT [EQ-TETRA_ISSI].ISSI,[EQ-TETRA_TEI].TEI, [EQ-TETRA_ISSI].Active," & _
" [EQ-TETRA_TEI].Activation, Client_Table.[Customer Name], Client_Table.[Customer ID], [EQ-TETRA_REQFUL].ReqType, SERVICEREQUEST_TABLE.REQNUM," & _
" SERVICEREQUEST_TABLE.REQDATE, SERVICEREQUEST_TABLE.RESPUSER" & _
" FROM ((Client_Table INNER JOIN [EQ-TETRA_ISSI] ON Client_Table.[External Customer Index] = [EQ-TETRA_ISSI].[Customer Index])" & _
" INNER JOIN SERVICEREQUEST_TABLE ON Client_Table.[External Customer Index] = SERVICEREQUEST_TABLE.Index) INNER JOIN ([EQ-TETRA_TEI]" & _
" INNER JOIN [EQ-TETRA_REQFUL] ON [EQ-TETRA_TEI].TEI = [EQ-TETRA_REQFUL].TEI) ON (SERVICEREQUEST_TABLE.REQNUM = [EQ-TETRA_REQFUL].Reqnum)" & _
" AND ([EQ-TETRA_ISSI].ISSI = [EQ-TETRA_REQFUL].ISSI)" & _
" WHERE [EQ-TETRA_TEI].TEI=[EQ-TETRA_REQFUL].[TEI] " _
& " AND [EQ-TETRA_ISSI].Active=True " _
& " AND [EQ-TETRA_TEI].Activation=True "
End If
strSQL=strSQL & " ORDER BY [EQ-TETRA_ISSI].ISSI;"
I'm also not convinced that you need to have [EQ-TETRA_TEI].TEI=[EQ-TETRA_REQFUL].[TEI] in the WHERE clause, as you are already using it to join two tables together.
Regards,

Running SQL Query In Access VBA

Im trying to run an SQL query in Access VBA but my query is too long to fit in one line
INSERT INTO tblProduct SELECT[SAMPartGrp],[ProductPrefix] ,[ProductCode] ,[pcode1],[pcode2],[SubPart1],[SubPart2],[ProductCodeNew],[ProductDescription],[MadeFrom],[MadeFromDescription],[Field1],[SamFamilySort1],[SamFamilySort2],[SamFamilySort3]
,[SamFamilySort4],[SamFamilySort5],[Grade],[Length],[Thickness],[fWidth],[Factor],[CubicMtrs],[CubicMtrsFull],[Weight(T)],[DrawingFilepath],[PackingFilePath],[EFACSProductGrouping],[BatchSize],[PackSize],[Density],[createdby],[createddate],[ProductType],[reorderpolicy],[EFACSExport],[PreactorExport],[customer],[Obsolete/DoNotUse],[noinminipack],[piecesincrate],[minipackheight],[DimA],[DimB],[DimC],[DimD],[DimE],[DimF],[DimG],[DimH],[DimI],[DimJ],[DimK],[DimL],[DimM],[DimN],[DimO] ,[DimP],[DimQ],[DimR],[DimS],[DimT],[DimU],[DimV],[DimW],[DimX],[DimY],[DimZ],[TolA],[TolB],[TolC],[TolD],[TolE],[TolF],[TolG],[TolH],[TolI],[TolJ],[TolK],[TolL],[TolM],[TolN],[TolO],[TolP],[TolQ],[TolR],[TolS],[TolT],[TolU],[TolV],[TolW],[TolX],[TolY],[TolZ]
,[Dimension],[Main],[Saws],[Moulders],[PaintLines],[XCut],[DET],[MitreSaw],[Wrapper],[Blocks]
,[HingeRecess],[ShrinkWrap],[CNC],[SW],[ShrinkWrapPackSize] ,[SAMBarCode],[machinedaway],[ExcludeFromPreactorUpload],[UseOtherM3XC],[UseOtherM3XC81],[UseOtherM3MS],[UseOtherM3MS83],[comment],[samtype1],[fsc],[LabelPack],[LabelPiece],[trml],[vtype1],[vtype2],[minipack] ,[profile],[madefromlength],[productchamp],[packtype],[uom],[acumatica],[Cupboard],[AcmtaExport],[ExportedtoAcmta],[PostingClass]
FROM tblProducts
so it wont run the full query at once, is there a workaround for this?
You have several issues.
One is that SQL server and Access SQL are not the same. Access SQL is a lot more limited, so just because an SQL query runs on the SQL server does not mean it will run in Access. To run SQL Server queries that are not Access SQL compatible you have to use a pass-through query.
The other issue is that Access table names and SQL server table names are no necessarily the same.
Now, assuming you have taken all that into account and your query is actually Access SQL compatible, you can run it like this:
Dim sql as String
sql = "Query part A"
sql = sql & "Query Part B"
... repeat as necessary
DoCmd.RunSQL sql
SQL doesn't take white space into account, this should run the entire query at once.
I think your problem is that you want to use SELECT INTO with TSQL
See here for more information:
https://msdn.microsoft.com/en-us/library/bb208934(v=office.12).aspx
Are you just talking about wraparound formatting, where you use the "& _" to continue your string?
strSQL = "SELECT [SAMPartGrp],[ProductPrefix] ,[ProductCode] ,[pcode1], " & _
"[pcode2], [SubPart1],[SubPart2],[ProductCodeNew],[ProductDescription], " & _
"[MadeFrom], [MadeFromDescription],[Field1],[SamFamilySort1], " & _
"[SamFamilySort2],[SamFamilySort3],[SamFamilySort4], " & _
"[SamFamilySort5], [Grade], "
Try this.
Dim strSQL as String
strSQL = "INSERT INTO tblProduct SELECT[SAMPartGrp],[ProductPrefix] , " & _
"[ProductCode] ,[pcode1],[pcode2],[SubPart1],[SubPart2],[ProductCodeNew], " & _
"[ProductDescription],[MadeFrom],[MadeFromDescription],[Field1], " & _
"[SamFamilySort1],[SamFamilySort2],[SamFamilySort3], [SamFamilySort4], " _
"[SamFamilySort5],[Grade],[Length],[Thickness], [fWidth],[Factor], " & _
"[CubicMtrs],[CubicMtrsFull],[Weight(T)],[DrawingFilepath], " & _
"[PackingFilePath],[EFACSProductGrouping],[BatchSize], " & _
"[PackSize],[Density],[createdby],[createddate],[ProductType], " & _
"[reorderpolicy],[EFACSExport],[PreactorExport],[customer], " & _
"[Obsolete/DoNotUse],[noinminipack],[piecesincrate], [minipackheight], " & _
"[DimA],[DimB],[DimC],[DimD],[DimE],[DimF],[DimG],[DimH], " & _
"[DimI],[DimJ],[DimK],[DimL],[DimM],[DimN],[DimO] ,[DimP], " &_
"[DimQ],[DimR],[DimS],[DimT],[DimU],[DimV],[DimW],[DimX], " & _
"[DimY],[DimZ],[TolA],[TolB],[TolC],[TolD],[TolE],[TolF], " & _
"[TolG],[TolH],[TolI],[TolJ],[TolK],[TolL],[TolM],[TolN], " & _
"[TolO],[TolP],[TolQ],[TolR],[TolS],[TolT],[TolU],[TolV], " & _
"[TolW],[TolX],[TolY],[TolZ],[Dimension],[Main],[Saws], " &_
"[Moulders],[PaintLines],[XCut],[DET],[MitreSaw],[Wrapper], " &_
"[Blocks],[HingeRecess],[ShrinkWrap],[CNC],[SW], " & _
"[ShrinkWrapPackSize] ,[SAMBarCode],[machinedaway], " & _
"[ExcludeFromPreactorUpload],[UseOtherM3XC],[UseOtherM3XC81], " & _
"[UseOtherM3MS],[UseOtherM3MS83],[comment],[samtype1],[fsc], " & _
"[LabelPack],[LabelPiece],[trml],[vtype1],[vtype2],[minipack] , " & _
"[profile],[madefromlength],[productchamp],[packtype],[uom], " & _
"[acumatica],[Cupboard],[AcmtaExport],[ExportedtoAcmta], " & _
"[PostingClass] FROM tblProducts;"
DoCmd.RunSQL strSQL

SQL query assistance needed with 'NOT'

I'm working out of VB6 with SQL SERVER 2012. I found myself in a pickle. Basically i have a query that works fine and pulls the necessary data in SQL SERVER, however, I'm having a difficult time translating it to vb6 SQL code. Here's a working query in SQL SERVER...
SELECT 'TotalSum' = SUM(Units)
FROM tblDetail
WHERE MemberID = '117'
AND CAST(SStartD AS DATETIME) >= '4/1/2016'
AND CAST(SStartD AS DATETIME) <= '4/7/2016'
AND Service = 166
AND [CODE] IN('1919')
AND NOT(InvoiceNo = '11880'
AND DtlNo = 2
)
AND NOT(InvoiceNo = '11880'
AND AdjNo = 2
);
So when I try to write it in my vb6 application i do something like
SELECT 'TotalSum' = SUM(Units)
FROM tblDetail
WHERE MemberID = '117'
AND CAST(SStartD AS DATETIME) >= '4/1/2016'
AND CAST(SStartD AS DATETIME) <= '4/7/2016'
AND Service = 166
AND [CODE] IN('1919')
AND (InvoiceNo <> '11880'
AND DtlNo <> 2
)
AND (InvoiceNo <> '11880'
AND AdjNo <> 2
);
However, this is not giving me the same results. Whats happening is in my last two clauses
( InvoiceNo <> '11880' AND DtlNo<> 2) AND (InvoiceNo <> '11880' AND AdjNo <> 2)
When I run them finally in SQL SERVER don't have paranthesis and its absolutely detrimental that the 2 seperate clauses are in paranthesis. Anyone know what I can do? I think my last resort might be to create a store procedure but i don't really want to do that.
EDIT:
g_SQL = "SELECT 'SUM' = SUM(Units) " & _
"FROM tblDetail WHERE " & _
"MemID = " & udtCDtl.Lines(udtCDtlIdx).MemID & " AND " & _
"CAST(SStartD As DateTime) >= '" & StartDate & "' AND " & _
"CAST(SStartD As DateTime) <= '" & DateAdd("d", -1, EndDate) & "' AND " & _
"Service = 166 AND " & _
"[CODE] IN (‘1919’)) And " & _
("InvoiceNo <> " & InvoiceDtlRS!InvoiceHdrNo & " OR " & _
"DtlNo <> " & (InvoiceDtlRS! InvoiceDtlNo, "")) & " AND " & _
("InvoiceNo <> " & InvoiceDtlRS!InvoiceHdrNo & " OR " & _
"AdjNo <> " & InvoiceDtlRS! InvoiceDtlNo)
Your translation of NOT(InvoiceNo = '11880' AND DtlNo = 2) to (InvoiceNo <> '11880' AND DtlNo <> 2) is incorrect.
In formal logic, !(A & B) is equivalent to (!A or !B), so it should be:
(InvoiceNo <> '11880' OR DtlNo <> 2)
This is why you're getting different results. However, why not use the original query? There's nothing in VB6 which would prevent it.
EDIT
g_SQL = "SELECT 'SUM' = SUM(Units) " & _
"FROM tblDetail WHERE " & _
"MemID = " & udtCDtl.Lines(udtCDtlIdx).MemID & " AND " & _
"CAST(SStartD As DateTime) >= '" & StartDate & "' AND " & _
"CAST(SStartD As DateTime) <= '" & DateAdd("d", -1, EndDate) & "' AND " & _
"Service = 166 AND " & _
"[CODE] IN (‘1919’)) And " & _
("InvoiceNo <> " & InvoiceDtlRS!InvoiceHdrNo & " OR " & _
"DtlNo <> " & (InvoiceDtlRS! InvoiceDtlNo, "")) & " AND " & _
("InvoiceNo <> " & InvoiceDtlRS!InvoiceHdrNo & " OR " & _
"AdjNo <> " & InvoiceDtlRS! InvoiceDtlNo)
You've got a ) in the wrong place twice. Also, the ) on the final live would be a syntax error I think. The last 5 lines should be:
"[CODE] IN (‘1919’) And " & _
("InvoiceNo <> " & InvoiceDtlRS!InvoiceHdrNo & " OR " & _
"DtlNo <> " & (InvoiceDtlRS!InvoiceDtlNo, "") & " AND " & _
("InvoiceNo <> " & InvoiceDtlRS!InvoiceHdrNo & " OR " & _
"AdjNo <> " & InvoiceDtlRS!InvoiceDtlNo & ")"
This should work. I'm able to use SQL queries using NOT with ADODB in VB6.
g_SQL = "SELECT 'SUM' = SUM(Units) " & _
"FROM tblDetail WHERE " & _
"MemID = " & udtCDtl.Lines(udtCDtlIdx).MemID & " AND " & _
"CAST(SStartD As DateTime) >= '" & StartDate & "' AND " & _
"CAST(SStartD As DateTime) <= '" & DateAdd("d", -1, EndDate) & "' AND " & _
"Service = 166 AND " & _
"[CODE] IN ('1919')) And " & _
"NOT (InvoiceNo = " & InvoiceDtlRS!InvoiceHdrNo & " AND DtlNo = " & InvoiceDtlRS!InvoiceDtlNo & ") AND " & _
"NOT (InvoiceNo = " & InvoiceDtlRS!InvoiceHdrNo & " AND AdjNo = " & InvoiceDtlRS!InvoiceDtlNo & ")"
While Marc may have given you a query that works, Simon's question is still valid. The only reason your original query wouldn't work is because you munged the quotes. You'll notice that your parentheses by the reference to InvoiceNo are outside the quotes rather than inside them (there are other problems as well, from changing your original query, but I'll leave you to figure those out for yourself). That makes them not part of the quoted string, and instead part of the VB6 expression. Frankly, Marc isn't doing you any favors by providing an alternative SQL query that happens to have all the VB6 syntax correct, while yours does not. The real problem is that you haven't worked out how to put a SQL query into a quoted string carefully enough.
You can't afford that kind of carelessness if you want to be good at what you're doing. I don't say this to be offensive, but to get your attention. By adopting Marc's solution as the correct one, you haven't really solved your problem, because your problem is a mindset that doesn't think about anything except getting something to work. That mindset makes for the worst kind of programmer, the kind that writes terrible code (hundreds of lines of code where it could be done in 10, for example) that makes nightmares for people who have to maintain it later. Don't be one of those people. When you don't know why something isn't working, go to the trouble of figuring out why. You only have to do it once for each problem, and that mindset will stand you well as you continue to develop your skills.
Again, no disrespect intended. I'm just trying to get you to understand how to avoid getting in "pickles" like this one in future. Hopefully, the next time you post a question here, the "pickle" you're in will be more sophisticated. :)
EDIT: I guess I'm not making myself clear enough. The simple rule is that you need to enclose everything in the working SQL query in quoted strings, and replace the literal search values with references to text boxes, fields, or whatever. So:
sql = "SELECT 'TotalSum' = SUM(Units) " & _
"FROM tblDetail " & _
"WHERE MemberID = '" & myVariable & "' " & _
"AND CAST(SStartD AS DATETIME) >= '" & myVariable & "' " & _
"AND CAST(SStartD AS DATETIME) <= '" & myVariable & "' " & _
"AND Service = 166 " & _
"AND [CODE] IN('1919') " & _
"AND NOT(InvoiceNo = '" & myVariable & "' " & _
"AND DtlNo = " & myVariable & _
")" & _
"AND NOT(InvoiceNo = '" & myVariable & "' " & _
"AND AdjNo = " & myVariable & _
");"
Where myVariable is whatever variable reference you want to replace your literal string with. Any examples you've given have errors in placement of double quotes, which is why you aren't getting the result you want, which is presumably a replication of your working SQL query. The reason Marc's works is not because he altered your original query (it doesn't look like he has, except to put it on less lines) but because he placed his quotation marks correctly. The reason your and simon's solutions don't work is because neither of you have. Going back to your original post, the reason that the parentheses fail to show is because you haven't enclosed them in quotes. Marc has.

Access 2007 Query Def Syntax Error

this is really frustrating and I'm hoping you can help me. I keep getting a syntax error no matter what I do on this query. I've read about putting parantheses on multiple joins but I did that and it doesn't work. What am I doing wrong here? Thanks for your time.
Set PTI = CurrentDb.CreateQueryDef("qry_PTImport", "SELECT DISTINCT" & _
" bl.LoanNumber" & _
", qcq.Code" & _
", t.ecType" & _
", eb.QueryNo" & _
", q.QueryName" & _
", q.Description" & _
", q.suggestedAction" & _
", bd.datetransfer" & _
", bd.datebrd " & _
"FROM ((((dbo.eCs_QCqueue qcq " & _
"JOIN dbo.eCs_Queries q ON q.QueryNo = eb.QueryNo) " & _
"JOIN brd_loan bl ON bl.serialID = qcq.serialID) " & _
"JOIN dbo.eCs_Type t ON t.ectypeid = q.ectypeid) " & _
"JOIN brd_deal bd ON bd.Code = bl.Code) " & _
"WHERE qcq.Code = '" & Deal & "'")
just wanted to say user HansUp was right in this instance of what my problem was. VBA doesn't do just JOINs.

SQL Query works in MS-Access but cannot implement it in vb.net form

The block of code immediately following (given to me by a stackoverflow solver) works perfectly in MS-Access. I'm trying to convert it to work in a vb.net form accessing the very same MS-Access database. I get an error and cannot see my mistake. Are there any vb.net coders that can see what I'm doing wrong. The first block of code works in MS-Access and is the code I'm trying to convert. And the second block of code is my conversion attempt.
SELECT at.animalID, amt.milestoneType
FROM
animals_Table at
LEFT JOIN
(
SELECT animalID, milestoneType
FROM animalMilestones_Table
WHERE milestoneType = 'Intake'
) amt
ON at.animalID = amt.animalID
Now, my conversion attempt:
dim selectAnimal as string
selectAnimal = "SELECT at.animalID, amt.milestoneType" & _
" FROM animals_Table at" & _
" LEFT JOIN" & _
" (" & _
" SELECT animalID, milestoneType" & _
" FROM animalMilestones_Table" & _
" WHERE milestoneType = '" & "Intake" & "'" & _
" ) amt" & _
" ON at.animalID = amt.animalID"
The error code I get is
!ErrorInfo.GetDescription failed with E_FAIL(0x80004005)
It appears that ACE.OLEDB doesn't like at as a table alias. Try this instead
Dim selectAnimal As String
selectAnimal = "SELECT atbl.animalID, amtbl.milestoneType" & _
" FROM animals_Table atbl" & _
" LEFT JOIN" & _
" (" & _
" SELECT animalID, milestoneType" & _
" FROM animalMilestones_Table" & _
" WHERE milestoneType = '" & "Intake" & "'" & _
" ) AS amtbl" & _
" ON atbl.animalID = amtbl.animalID"