VBA trouble with SQL - sql

I'm using this code for an Access 2010 database, and I seem to have a problem with the syntax of my SQL statement, but I can't for the life of me figure out how to correctly format the statement. Thank you in advance for any help!
qdf = db.CreateQueryDef("Company_State_Q")
Dim strSQLSearch As String
strSQLSearch = "SELECT [Company Information].Company_Name, " & _
"[Company Information].Industry" & _
"FROM Company Information" & _
"WHERE [Company Information].State ='" & stateV & "'" & _
"ORDER BY [Company Information].Company_Name;"
qdf.SQL = strSQLSearch

You should use ...
Debug.Print strSQLSearch
... in your code after you build the strSQLSearch string. You can then view the string in the Immediate window (go there with Ctrl+g).
From the Immediate window I set the value of stateV to "CA" and tested your string like this:
stateV = "CA" : ? "SELECT [Company Information].Company_Name, " & _
"[Company Information].Industry" & _
"FROM Company Information" & _
"WHERE [Company Information].State ='" & stateV & "'" & _
"ORDER BY [Company Information].Company_Name;"
SELECT [Company Information].Company_Name, [Company Information].IndustryFROM Company InformationWHERE [Company Information].State ='CA'ORDER BY [Company Information].Company_Name;
Once you actually see the completed strSQLSearch string, it's easy to spot multiple problems:
IndustryFROM should be Industry FROM
FROM Company Information should be FROM [Company Information]
InformationWHERE should be Information WHERE
'CA'ORDER should be 'CA' ORDER
Consider using line breaks between the sections of your SELECT statement. The db engine is perfectly happy with line breaks instead of spaces. And you may find it easier to read the statement as several short lines rather than as one long line.
Dim strSQLSearch As String
strSQLSearch = "SELECT ci.Company_Name, ci.Industry" & vbCrLf & _
"FROM [Company Information] AS ci" & vbCrLf & _
"WHERE ci.State ='" & stateV & "'" & vbCrLf & _
"ORDER BY ci.Company_Name;"
Debug.Print strSQLSearch
Also at the beginning of your code you have ...
qdf = db.CreateQueryDef("Company_State_Q")
It seems qdf must be a DAO.QueryDef object, so I think you should use the Set keyword to assign to it.
Set qdf = db.CreateQueryDef("Company_State_Q")

Related

MS ACCESS - VBA - Insert Into SQL adds unwanted data to top of table on form refresh

The below code appends a templated bill of materials to a job card. It adds part and job number to the end of tblMaterialRequiremnt table.. and works!
Private Sub Command15_Click()
Dim db As DAO.Database
Dim strSQL As String
Dim PrtNbrGt As String
Dim JbNum As String
JbNum = Me.[tblManufactured.Job Number]
PrtNbrGt = Me.SCSPartNumb
Set db = CurrentDb
strSQL = "INSERT INTO tblMaterialRequiremnt ( [Customer Part Number], [Job Number] ) " & vbCrLf & _
"SELECT tbl_BOM_Requirments.RequiredMaterialPrtNum, '" & JbNum & "'" & vbCrLf & _
"FROM tbl_BOM_Requirments " & vbCrLf & _
"WHERE (tbl_BOM_Requirments.PrtNmber_LinkField) = """ & PrtNbrGt & """"
db.Execute strSQL
'Me.Form.Requery
Me.Form.Refresh
End Sub
The problem is when the form is refreshed the job number is being incorrectly overwritten on the 1st line (IE at the top) of the tblMaterialRequiremnt table..
yet there is nothing in the code to suggest updating the 1st record..
Any ideas why a refresh would overwrite the first job number field?

How to Pass SQL Parameter to Form Using OpenArgs?

I have a Database (not built by me) that uses 3 separate forms to accomplish 1 thing.
I would instead like to pass a SQL string to the OpenArgs in order to utilize 1 form.
Original Code for form I'd like to utilize:
Private Sub Form_Open(Cancel As Integer)
Dim strSQL As String
If Not IsNull(Me.OpenArgs) Then
strSQL = "SELECT tbl_COMBINED.[First Name] AS [Name Badge], 'P' AS Logo, Format(Now(),""yyyy"") & STOCKHOLDERS MEETING' AS MEETING " _
& "FROM tbl_COMBINED " _
& "GROUP BY tbl_COMBINED.[First Name], 'P', Format(Now(),""yyyy"") & ' STOCKHOLDERS MEETING', " _
& "tbl_COMBINED.ACCOUNT, tbl_COMBINED.Came " _
& "HAVING tbl_COMBINED.ACCOUNT = '" & CStr(Me.OpenArgs) & "' " _
& "AND ((tbl_COMBINED.Came) Is Null Or (tbl_COMBINED.Came)) = 0"
Me.RecordSource = strSQL
End If
End Sub
Each of the other forms is called by using
DoCmd.OpenForm "frm_newmanualnamebadge", "", "",, acNormal
from the Main form and has the SQL string in the row source. I would like to eliminate the row source and utilize the 1 form. I set the string from each button to:
strManuel = "SELECT tbl_manual_name_badge.NAMEBADGE1, tbl_manual_name_badge.MEETING, " _
& "tbl_manual_name_badge.LOGO, tbl_manual_name_badge.Stockerholder " _
& "FROM tbl_manual_name_badge"
DoCmd.OpenForm "frm_newmanualnamebadge", "", "",, acNormal, strManual
Passing the strManual to the form as a SQL string, however, every time I run it I get a "#Name?" in the name field instead of the name entered.
Here is the code I used on the form:
If Not IsNull(Me.OpenArgs) Then
strSQL = "SELECT tbl_COMBINED.[First Name] AS [Name Badge], 'P' AS Logo " _
& "FROM tbl_COMBINED " _
& "GROUP BY tbl_COMBINED.[First Name], 'P', " _
& "tbl_COMBINED.ACCOUNT, tbl_COMBINED.Came " _
& "HAVING tbl_COMBINED.ACCOUNT = '" & CStr(Me.OpenArgs) & "' " _
& "AND ((tbl_COMBINED.Came) Is Null Or (tbl_COMBINED.Came)) = 0"
Me.RecordSource = strSQL
ElseIf IsNull(Me.OpenArgs) Then
strSQL = "SELECT tbl_manual_name_badge.NAMEBADGE1, tbl_manual_name_badge.MEETING, " _
& "tbl_manual_name_badge.LOGO, tbl_manual_name_badge.Stockerholder " _
& "FROM tbl_manual_name_badge"
Me.RecordSource = strSQL
End If
Well, you either pass one value, or you pass the whole sql string.
But, if you passing the WHOLE sql string for the form, then this makes no sense:
If Not IsNull(Me.OpenArgs) Then
strSQL = "SELECT tbl_COMBINED.[First Name] AS [Name Badge], 'P' AS Logo " _
& "FROM tbl_COMBINED " _
& "GROUP BY tbl_COMBINED.[First Name], 'P', " _
& "tbl_COMBINED.ACCOUNT, tbl_COMBINED.Came " _
& "HAVING tbl_COMBINED.ACCOUNT = '" & CStr(Me.OpenArgs) & "' " _
& "AND ((tbl_COMBINED.Came) Is Null Or (tbl_COMBINED.Came)) = 0"
Me.RecordSource = strSQL
I mean, OpenArgs is a WHOLE sel string, and I am VERY sure that ACCOUNT = " some huge sql string" will NEVER work.
So, you would want this:
Dim strSQL As String
If Not IsNull(Me.OpenArgs) Then
strSQL = me.OpenArgs
else
strSQL = "SELECT tbl_manual_name_badge.NAMEBADGE1, tbl_manual_name_badge.MEETING, " _
& "tbl_manual_name_badge.LOGO, tbl_manual_name_badge.Stockerholder " _
& "FROM tbl_manual_name_badge"
End If
Me.RecordSource = strSQL
So, our logic is now:
if passed sql string (openargs), then that becomes our sql
if no open arges, then use the defined sql we have in the on-load

SQL getting name from userform

I am having a little trouble with my SQL in access
CurrentDb.Execute "INSERT INTO _tbl_Structure " & _
"SELECT * " & _
"FROM [MS Access;pwd=" & strPassword & ";database=" & DBpath & "\" & DBname & "].[" & tblStructure & "] " & _
"WHERE [user] = '" & [Forms!frm_Advisors_Stats-manager].[Position]
The issue appears to be with
[Forms!frm_Advisors_Stats-manager].[Position]
Any help on what I am doing wrong here?
The position textbox shows if the person logged in is a manager or not. If they are a manager as stated on the userform is pulls all records the manager has on the team
The error shown is:
External name not defined
Or use correct bracketing:
[Forms]![frm_Advisors_Stats-manager]![Position]
Since you're using string concatenation, your object notation needs to be valid for VBA. Since your object name contains a hyphen, you need to properly refer to it using the forms collection and without the bang operator.
"WHERE [user] = '" & Forms("frm_Advisors_Stats-manager").Position.Value & "'"
Another way to reference a control on a form that I used a lot is:
Form_Advisors_Stats-manager.Position
Therefore:
CurrentDb.Execute "INSERT INTO _tbl_Structure " & _
"SELECT * " & _
"FROM [MS Access;pwd=" & strPassword & ";database=" & DBpath & "\" & DBname & "].[" & tblStructure & "] " & _
"WHERE [user] = '" & Form_Advisors_Stats-manager.Position & "'"

How can I do a simple join on a subquery?

I've been at this for 2 hours and have no idea what the issue is. Although I have worked a fair amount with SQL, I'm struggling with the idiosyncrasies in Access queries relative to SQL queries when using the ADO ACE connection to query Excel worksheets. My goal at it's most basic is to do a join with a subquery. I have simplified the query considerably to display the issue, so please excuse the fact that it wouldn't really make sense to run a query like this.
The error I keep getting is Syntax Error in From Clause. The worksheet only has 2 columns, Account Number and Cost
Sub stackoverflow()
Dim acctcon As New ADODB.Connection
Dim acctrec As New ADODB.Recordset
acctcon.ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users\name\Documents\Book1.xlsx;" & _
"Extended Properties=" & Chr(34) & "Excel 12.0 Xml;HDR=YES" & Chr(34) & ";"
acctcon.Open
querystr = "Select [Accounts$].[Account Number], [mm].[Cost] " & _
"FROM [Accounts$] " & _
"JOIN (Select [Account Number], [Cost] " & _
"FROM [Accounts$]) As mm " & _
"ON [Accounts$].[Account Number] = [mm].[Account Number]"
acctrec.Open querystr, acctcon
'Syntax Error on From Clause
End Sub
Try to reset the Close bracket behind As mm
querystr = "Select [Accounts$].[Account Number], [mm].[Cost] " & _
"FROM [Accounts$] " & _
"INNER JOIN (Select [Account Number], [Cost] " & _
"FROM [Accounts$] As mm) " & _
"ON [Accounts$].[Account Number] = [mm].[Account Number]"
But you have to replace the inner join, because it makes no sense like #krish KM stated. I suppose you took it as a placeholder.

Running a parameter query in Access VBA

I am trying to run the following query in a VBA function. I keep getting "Too few parameters. Expected 1."
strSQL = "Parameters [Report Date] DateTime;" & vbCrLf & _
"SELECT SCF.code AS [Stock Code], " & vbCrLf & _
"SCF.desc AS [Description], " & vbCrLf & _
"SCF.grp AS [Product Group]," & vbCrLf & _
"SCF.qCurr AS [Closing Stock], " & vbCrLf & _
"SCF.abp AS [Avg Price], " & vbCrLf & _
"Sum(([Closing Stock]*[Avg Price])) AS [STOCK VALUE], " & vbCrLf & _
"MaxDate.tDate AS [Last Transaction Date], " & vbCrLf & _
"Sum(IIf(([Last Transaction Date]>[Report Date]),([Closing Stock]*[Avg Price]),0)) AS [After Report Date], " & vbCrLf & _
"DateDiff(""d"",[Last Transaction Date],[Report Date]) AS [Days since Last Transaction], " & vbCrLf & _
"[Report Date]" & vbCrLf & _
"INTO [FinReport] " & vbCrLf & _
"FROM SCF RIGHT JOIN MaxDate ON MaxDate.parent = SCF.this "
strSQL = strSQL & _
"WHERE (SCF.qCurr <> 0) " & vbCrLf & _
"GROUP BY SCF.code, " & vbCrLf & _
"SCF.desc, " & vbCrLf & _
"SCF.grp, " & vbCrLf & _
"SCF.qCurr, " & vbCrLf & _
"SCF.abp, " & vbCrLf & _
"MaxDate.tDate" & vbCrLf & _
"ORDER BY MaxDate.tDate;"
Set qdf = db.CreateQueryDef("", strSQL)
qdf.Parameters("[Report Date]").Value = Form_IO_Form.ReportDate_TB.Value
qdf.Execute
I have verified that all fields (other than [Report Date] of course) exist and the query runs by itself as an access query (pop up asks for [Report Date]).
Help!
Edit 1:
As requested here is the DB file as a ZIP. It is an Access 2007 .accdb file
DB File
Your SQL statement will trigger error #3122 from the db engine:
You tried to execute a query that does not include the specified expression 'DateDiff("d",[Last Transaction Date],[Report Date])' as part of an aggregate function.
That error will cause the statement to fail before the db engine even considers any parameters.
When you build a SQL statement with VBA, it's better to start with one the db engine will accept. Then you should also follow the sound advice from #mwolfe02 to Debug.Print strSQL ... to give yourself an opportunity to examine the completed statement you're asking the db engine to execute.
Edit: Having examined the ACCDB file you uploaded, I still don't understand why your query doesn't trigger error #3122. However the query does work as a saved query and can work when you execute it from VBA code. The reason you got the complaint about "too few parameters" is that you weren't actually executing the temporary QueryDef you created. Instead you were attempting to execute the SQL text like this:
' Execute created Query '
CurrentDb.Execute strSQL, dbFailOnError
If you change to this approach (as you indicated in your question), it works without error:
qdf.Execute
I am guessing that you have a typo in one of your field names. The easiest way to find it is to throw a Debug.Print strSQL line immediately before your Set qdf... line.
Then create a new query in the Access UI, switch to SQL view, paste in the SQL text from the immediate window, and execute the query. Access will prompt you for the Report Date (which you are expecting) and the mistyped name of one of your fields.