MS-Access VBA select query with multiple criteria - sql

I have a dropdown box in an MS Access form which is populated by the following select query:
strSQL = "SELECT [Process] " _
& "FROM [dbo_tbl_Area_Process] " _
& "WHERE Area=" & Chr(34) & Me.Area_NC_Occurred & Chr(34) & ";"
Me.Process.RowSource = strSQL
I would like to add Active = -1 as a second criteria to the query to further limit the selections.
I have tried, so far unsuccessfully to add this second criteria and am at a loss as to how to proceed. Any help from the community would be most appreciated.
I have tried the following where conditions:
& "WHERE Area=" & Chr(34) & Me.Area_NC_Occurred & Chr(34) & " and Active =-1"
This does not return any results.
& "WHERE Area=" & Chr(34) & Me.Area_NC_Occurred & Chr(34) & " and Active ="-1""
This has a compile error:
Expected:end of statement

Following on from mintys comment regarding linked SQL server tables I changed the query to the following:
strSQL = "SELECT dbo_Tbl_Area_Process.Process " _
& "FROM dbo_Tbl_Area_Process " _
& "WHERE Area=" & Chr(34) & Me.Area_NC_Occurred & Chr(34) & " AND Active=True"
Adding the table references to the SELECT and FROM lines gives me the outputs I expected.
Thanks all for your comments

Related

Run-time error ‘3061’: Too few parameters expected 1

i had this error when i was trying to INSERT records to a local table with VBA.
I have checked the data type and putting in the quotes for the the short text data type but it doesn't work.
table_newid = "SELECT Cint(t1." & id_name(i) & "_new), " & Replace(select_column_str, local_table_name, "t2") & " FROM " & vbCrLf & _
"(SELECT CInt(DCount(""[" & id_name(i) & "]"", """ & qry_distinct_id_name & """, ""[" & id_name(i) & "]<="" & [" & id_name(i) & "])) as " & id_name(i) & "_new, * FROM " & qry_distinct_id_name & ") AS t1 " & vbCrLf & _
"LEFT JOIN " & local_table_name & "_ALL as t2 " & vbCrLf & _
"ON t1." & id_name(i) & " = t2." & id_name(i) & " " & vbCrLf & _
"WHERE t2.database = '" & database_name & "'"
strQuery = "INSERT INTO " & local_table_name & "_temp (" & temp_field(i) & ", " & Replace(select_column_str, local_table_name & ".", "") & ") " & vbCrLf & table_newid
Debug.Print strQuery
DoCmd.SetWarnings False
db.Execute strQuery
DoCmd.SetWarnings True
From the debug.print, i have got:
INSERT INTO TblLUMachineTypes_temp (MachTypeID_new, MachTypeID, MachTypeCode, MachTypeMod, MachTypeDesc, MachTypeDisc, NewCode, Approved, mttime, CreatedBy, CreatedTS, ModifiedBy, ModifiedTS)
SELECT t1.MachTypeID_new, t2.MachTypeID, t2.MachTypeCode, t2.MachTypeMod, t2.MachTypeDesc, t2.MachTypeDisc, t2.NewCode, t2.Approved, t2.mttime, t2.CreatedBy, t2.CreatedTS, t2.ModifiedBy, t2.ModifiedTS FROM
(SELECT CInt(DCount("[MachTypeID]", "qry_TblLUMachineTypes_id_distinct", "[MachTypeID]<=" & [MachTypeID])) as MachTypeID_new, * FROM qry_TblLUMachineTypes_id_distinct) AS t1
LEFT JOIN TblLUMachineTypes_ALL as t2
ON t1.MachTypeID = t2.MachTypeID
WHERE t2.database = 'CPM-252-2'
When i copied this query and execute it manually, it works fine but not with VBA. Any idea?
Thanks in advance.
Remove all the & vbCrLf from your code, they are not necessary and I assume they corrupt the SQL syntax.
I found the problem. I found that qry_distinct_id_name query table has a Dlookup function in there that returns a string value, which will work when executing the query manual but doesn't work when you run it with VBA. So I have re-written the code to put in the quote before and after dlookup() function.

When I write code inside textbox doesn't accept it

I have a textbox in a form. I use this textbox to write "Codes" and then I save it in the table in the database through the SQL insert statement, but the code doesn't accept to run and gives me an error message:
Run-Time error '3075'.
type of database: Access database
type of field data: LongText
What the problem and how to pass all same problems when I need to save codes inside the database field.
When I try to save the code without (') it's working!
I use this SQL Statement:
CurrentDb.Execute "Update Tbl_Codes Set [LP_ID]= " & Me.txtID & ",
[Code_Title]='" & Me.txtTitle & "'" _
& " ,[Code_Des]= '" & Me.txtDes & "',[Code_Key]= '" & Me.txtKey & "',
[Notes]= '" & Me.txtNotes & "'" _
& " Where [ID]= " & Me.txtID1 & ""
And I want to save this Code:
DSum("Field1";"Table";"Field2= '" & Value & "'")
Please change your code as follows. You need to escape single quotes by doubling them up. A simple replace will work for your.
CurrentDb.Execute "Update Tbl_Codes Set [LP_ID]= " & Replace(Me.txtID,"'","''") & ",
[Code_Title]='" & Replace(Me.txtTitle,"'","''") & "'" _
& " ,[Code_Des]= '" & Replace(Me.txtDes,"'","''") & "',[Code_Key]= '" & Replace(Me.txtKey,"'","''") & "',
[Notes]= '" & Replace(Me.txtNotes,"'","''") & "'" _
& " Where [ID]= " & Me.txtID1 & ""
DSum("Field1";"Table";"Field2= '" & Replace(Value,"'","''") & "'")

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 & "'"

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

Selecting data based on multiple fields (Where And)

I have large amounts of data that I am trying to sort out based on two cascading combo boxes. I get error Microsoft Access can't find the field '|1' referred to in your expression and it points me to:
ElseIf [Forms]![Send To GE]![cboFil] = "LCP" Then
strSQL = "Select * From [To_GE] Where [Community] = " & Chr(34) & Me.cboSubFil.Value & Chr(34) And [LCP] = "& Chr(34) & Me.cboSSubFil.Value & Chr(34)"
Set rst = db.OpenRecordset(strSQL)
It seems that the And should work for this. What's causing this error, and how can I resolve it?
strSQL = "Select * From [To_GE] Where [Community] = " & Chr(34) & Me.cboSubFil.Value & Chr(34) And [LCP] = "& Chr(34) & Me.cboSSubFil.Value & Chr(34)"
Should maybe be
strSQL = "Select * From [To_GE] Where [Community] = " & Chr(34) & Me.cboSubFil.Value & Chr(34) & " And [LCP] = " & Chr(34) & Me.cboSSubFil.Value & Chr(34)
To make things read a little easier though I would recommend escaping your quotes or switching to single quotes in the query
strSQL = "Select * From [To_GE] Where [Community] = '" & Me.cboSubFil.Value & "' And [LCP] = '" & Me.cboSSubFil.Value & "'"