I keep recieving compiling errors saying that txtlln in the where line cannot be found. I am fairly new to SQL/VBA so I am not sure I am using the correct expressions to have this work.
Private Sub btnlledit_Click()
Dim strSQL As String
SQL = "UPDATE tblll " & _
"SET [Component/Product] = '" & Forms!frmaddll!txtllcomponent & "',[HN] = '" & Forms!frmaddll!txtllhn & "' " & _
"WHERE [LLN] = '" & Forms!frmaddll!txtlln.value & "';"
debug.print sql
DoCmd.RunSQL strSQL
DoCmd.SetWarnings True
DoCmd.Requery
Me.Refresh
End Sub
You seem to have a few issues swith your string concatenation.
Private Sub btnlledit_Click()
Dim strSQL As String
SQL = "UPDATE tblll " & _
"SET [Component/Product] = '" & Forms!frmaddll!txtllcomponent & "' " & _
"WHERE [LLN] = '" & Forms!frmaddll!txtlln.value & "';"
debug.print sql
DoCmd.RunSQL strSQL
DoCmd.SetWarnings True
DoCmd.Requery
Me.Refresh
End Sub
Related
This is wrecking my brains for 4 hours now,
I have a Table named BreakSked,
and I this button to update the table with the break end time with this sql:
strSQL1 = "UPDATE [BreakSked] SET [BreakSked].[EndTime] = " & _
Me.Text412.Value & " WHERE [BreakSked].AgentName = " & Me.List423.Value _
& " AND [BreakSked].ShiftStatus = '1'"
CurrentDB.Execute strSQL1
Text412 holds the current system time and List423 contains the name of the person.
I'm always getting this
"Run-time error 3075: Syntax Error (missing operator) in query
expression '03:00:00 am'
Any help please?
EDIT: Thanks, now my records are updating. But now its adding another record instead of updating the record at hand. I feel so silly since my program only has two buttons and I can't figure out why this is happening.
Private Sub Form_Load()
DoCmd.GoToRecord , , acNewRec
End Sub
Private Sub Command536_Click()
strSQL1 = "UPDATE BreakSked SET BreakSked.EndTime = '" & Me.Text412.Value & "',BreakSked.Duration = '" & durationz & "' " & vbCrLf & _
"WHERE (([BreakSked].[AgentID]='" & Me.List423.Value & "'));"
CurrentDb.Execute strSQL1
CurrentDb.Close
MsgBox "OK", vbOKOnly, "Added"
End Sub
Private Sub Command520_Click()
strSql = "INSERT INTO BreakSked (ShiftDate,AgentID,StartTime,Status) VALUES ('" & Me.Text373.Value & "', '" & Me.List423.Value & "', '" & Me.Text373.Value & "','" & Me.Page657.Caption & "')"
CurrentDb.Execute strSql
CurrentDb.Close
MsgBox "OK", vbOKOnly, "Added"
End Sub
You wouldn't need to delimit Date/Time and text values if you use a parameter query.
Dim strUpdate As String
Dim db As DAO.Database
Dim qdf As DAO.QueryDef
strUpdate = "PARAMETERS pEndTime DateTime, pAgentName Text ( 255 );" & vbCrLf & _
"UPDATE BreakSked AS b SET b.EndTime = [pEndTime]" & vbCrLf & _
"WHERE b.AgentName = [pAgentName] AND b.ShiftStatus = '1';"
Debug.Print strUpdate ' <- inspect this in Immediate window ...
' Ctrl+g will take you there
Set db = CurrentDb
Set qdf = db.CreateQueryDef("", strUpdate)
qdf.Parameters("pEndTime").Value = Me.Text412.Value
qdf.Parameters("pAgentName").Value = Me.List423.Value
qdf.Execute dbFailOnError
And if you always want to put the current system time into EndTime, you can use the Time() function instead of pulling it from a text box.
'qdf.Parameters("pEndTime").Value = Me.Text412.Value
qdf.Parameters("pEndTime").Value = Time() ' or Now() if you want date and time
However, if that is the case, you could just hard-code the function name into the SQL and dispense with one parameter.
"UPDATE BreakSked AS b SET b.EndTime = Time()" & vbCrLf & _
As I said in my comment you need to wrap date fields in "#" and string fields in escaped double quotes
strSQL1 = "UPDATE [BreakSked] SET [BreakSked].[EndTime] = #" & _
Me.Text412.Value & "# WHERE [BreakSked].AgentName = """ & Me.List423.Value & _
""" AND [BreakSked].ShiftStatus = '1'"
I have a few controls (Combobox's I call DDL's) that I use as filters for a dynamic query, shown below.
I have a region, division filter - and BCI/BCV/ABC/etc dropdowns.
When I select the region and division, the output list box correctly filters out everything except THOSE region/divisions. Good.
The problem comes in when I use the other DDL's, ABD/BCI/etc... those do not filter out correctly and I think it is with my and/or clauses below.
Can anyone see anything glaring or point me in the right direction to get this so that every control and ddl element filters out the data it is intended for - while keeping it in a format where the SQL itself is part of a string, like in my example?
Private Sub goBtn_Click()
strSQL = "SELECT [account_number], [BCI_Amt], [BCV_Amt],[ABC_Amt], [other_Amt], " & _
"[BCI_Amt]+[BCV_Amt]+[ABC_Amt]+[other_MRC_Amt], Division_Name, Region_Name, " & _
"Tier, Unit_ID, Name, Description_2 " & _
"FROM dbo_ndw_bc_subs " & _
"WHERE DivisionDDL = [Division_Name] and RegionDDL = [Region_Name] " & _
" and ( [BCI_Ind] = CheckBCI.value or [BCV_Ind] = CheckBCV.value or [ABC_Ind] = CheckABC.value " & _
" or BCIServiceDDL = [Tier]" & _
" or BCVServiceDDL = [Description_2]" & _
" or ABCServiceDDL = [Unit_ID] )" & _
"ORDER BY 6 asc"
Me.output1.RowSource = strSQL
End Sub
One of the combo box DDL control codes. There are check boxes that make the combo box visible or not visible.
Private Sub CheckBCV_Click()
If Me.CheckBCV = vbTrue Then
Me.BCVServiceDDL.Visible = True
Me.BCVServiceDDL = "Select:"
strSQL = "SELECT Distinct subs.[Description_2] FROM dbo_ndw_bc_subs "
Me.BCVServiceDDL.RowSource = strSQL
Me.BCVServiceDDL.Requery
Else
Me.BCVServiceDDL.Visible = False
Me.BCVServiceDDL = ""
End If
End Sub
Edit: Added additional code to the first code block for context, and updated some comments.
To reiterate the point of my question - Since some of the DDL's work as expected while the others do not. Is it in the AND/OR section where I have a problem - or am I forced to do an IF/IIF statement in the select. (And if I do this IF solution - how would that be incorporated into a string the way I have it now, I have not seen an example of this in my research on a resolution).
I think your top code sample should read more like this:
Private Sub goBtn_Click()
Dim strSQL As String
Dim strWhere As String
Dim strOp As String
strSQL = "SELECT [account_number], [BCI_Amt], [BCV_Amt],[ABC_Amt], [other_Amt], " & _
"[BCI_Amt]+[BCV_Amt]+[ABC_Amt]+[other_MRC_Amt], Division_Name, Region_Name, " & _
"Tier, Unit_ID, Name, Description_2 " & _
"FROM dbo_ndw_bc_subs "
strWhere = ""
strOp = ""
If Not IsNull(Me.DivisionDDL.Value) Then
strWhere = strWhere & strOp & "(Division_Name = """ & Me.DivisionDDL.Value & """)"
strOp = " And "
End If
If Not IsNull(Me.RegionDDL.Value) Then
strWhere = strWhere & strOp & "(Region_Name = """ & Me.RegionDDL.Value & """)"
strOp = " And "
End If
If Me.CheckBCI.Value Then
strWhere = strWhere & strOp & "(Tier = """ & Me.BCIServiceDDL.Value & """)"
strOp = " And "
End If
If Me.CheckBCV.Value Then
strWhere = strWhere & strOp & "(Description_2 = """ & Me.BCVServiceDDL.Value & """)"
strOp = " And "
End If
If Me.CheckABC.Value Then
strWhere = strWhere & strOp & "(Unit_ID = """ & Me.ABCServiceDDL.Value & """)"
strOp = " And "
End If
If Len(strWhere) > 0 then
strSQL = strSQL & " WHERE " & strWhere
End If
strSQL = strSQL & " ORDER BY 6 asc"
Me.output1.RowSource = strSQL
End Sub
This is wordier, but much closer to correct. P.S. I guessed that all values are strings. If not remove the quoting around non-string values.
I have a macro that pulls from an Access DB and writes the recordset to the spreadsheet based upon dates that are entered into a userform. However, if I enter in "3/2/2105" and "3/5/2015" it returns all the records from 3/2-3/5 and then 3/20-3/31. I cannot think of any reason why it would do this. If anybody could point me in the right direction/make suggestions it would be greatly appreciated.
Sub pullfrommsaccess()
queryform.Show
Dim conn As Object
Dim rs As Object
Dim AccessFile As String
Dim SQL As String
Dim startdate As String
Dim enddate As String
Dim i As Integer
Sheet2.Cells.Delete
Application.ScreenUpdating = False
AccessFile = ThisWorkbook.Path & "\" & "mdidatabase.accdb"
On Error Resume Next
Set conn = CreateObject("ADODB.connection")
If Err.Number <> 0 Then
MsgBox "Connection was not created!", vbCritical, "Connection Error"
Exit Sub
End If
On Error GoTo 0
conn.Open "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & AccessFile
If tblname = "Attainments" Then
If shift1 = "1" Then
SQL = "SELECT [Line],[Area],[Shift],[Attainment Percentage],[Date] FROM " & tblname & " WHERE Shift='1' and Date Between " & "'" & pastdate & "' " & "and" & " '" & currentdate & "'"
End If
If shift2 = "2" Then
SQL = "SELECT [Line],[Area],[Shift],[Attainment Percentage],[Date] FROM " & tblname & " WHERE Shift='2' and Date Between " & "'" & pastdate & "' " & "and" & " '" & currentdate & "'"
End If
If shift1 = "1" And shift2 = "2" Then
SQL = "SELECT [Line],[Area],[Shift],[Attainment Percentage],[Date] FROM " & tblname & " WHERE Date Between " & "'" & pastdate & "' " & "and" & " '" & currentdate & "'"
End If
End If
If tblname = "MDItable" Then
If shift1misses = "1" Then
SQL = "SELECT [Date],[Area],[Shift],[Line],[Quantity],[Issue] FROM " & tblname & " WHERE Shift='1' and Date Between " & "'" & pastdatemisses & "' " & "and" & " '" & currentdatemisses & "'"
End If
If shift2misses = "2" Then
SQL = "SELECT [Date],[Area],[Shift],[Line],[Quantity],[Issue] FROM " & tblname & " WHERE Shift='2' and Date Between " & "'" & pastdatemisses & "' " & "and" & " '" & currentdatemisses & "'"
End If
If shift1misses = "1" And shift2misses = "2" Then
SQL = "SELECT [Date],[Area],[Shift],[Line],[Quantity],[Issue] FROM " & tblname & " WHERE Date Between " & "'" & pastdatemisses & "' " & "and" & " '" & currentdatemisses & "'"
End If
End If
On Error Resume Next
Set rs = CreateObject("ADODB.Recordset")
If Err.Number <> 0 Then
Set rs = Nothing
Set conn = Nothing
MsgBox "Recordset was not created!", vbCritical, "Recordset Error"
Exit Sub
End If
On Error GoTo 0
rs.CursorLocation = 3
rs.CursorType = 1
rs.Open SQL, conn
If rs.EOF And rs.BOF Then
rs.Close
conn.Close
Set rs = Nothing
Set conn = Nothing
Application.ScreenUpdating = True
MsgBox "There are no records in the recordset!", vbCritical, "No Records"
Exit Sub
End If
For i = 0 To rs.Fields.Count - 1
Sheet2.Cells(1, i + 1) = rs.Fields(i).Name
Next i
'Copy From RecordSet to Excel and Reset
Sheet2.Range("A2").CopyFromRecordset rs
rs.Close
conn.Close
Set rs = Nothing
Set conn = Nothing
MsgBox "The records from " & pastdate & " and " & currentdate & " were successfully retrieved from the '" & tblname & "' table!", vbInformation, "Done"
End If
Call TrimALL
End Sub
You have a field named Date, try renaming that and reworking the code as in first instance that's a reserved word and is a bad idea for starters!
When working with dates, see Allen Browne's comments on the matter here for consistency;
http://allenbrowne.com/ser-36.html
You have your dates declared as string, but in your SQL query you're surrounding them with a ' not a #. It should read;
Date Between " & "#" & pastdate & "# " & "and" & " #" & currentdate & "#"
All of the above should sort you out, if not comment and I'll take a much closer look for you!
I'm having some problems with a VBA script I'm creating and I thought here would be the best place to ask. I will give some background:
I am writing this program as a lot of my clients go against the regular issued documents from my countries tax office and pay cash in hand, and then get me to calculate the amount of tax on that particular amount. It is a fair bit of paperwork figuring that out manually, so I am writing an application that does this, and a fair amount more. The script below is at the heart of what needs to be done.
For the first use case I have essentially created a single-use form in Access - nothing is written, it is just for a temporary calculation and being sent to the printer - to calculate holiday pay.
As I cannot perform a SQL lookup in a calculated cell, I am running a VBA script to do the heavy lifting for me, passing the three entered values as arguments.
However, I cannot seem to get rid of runtime error 3075, and I cannot for the life of me figure out where it is coming from. I have traced it down to the SQL statement but I can't find where there would be an operator error. Where am I going wrong?
Here is the code:
Option Compare Database
Public Function DetermineTax(CurrentDate As Date, CurrWageType As String, CalcNetWages As Currency)
'Checks whether required fields are blank
If Not (IsDate(CurrentDate)) Then
Exit Function
End If
If (CurrWageType = "") Then
Exit Function
End If
If (CalcNetWages <= CCur(0#)) Then
Exit Function
End If
Dim strSQL As String
'Calculates tax based on (-((n-b)/(a-1))-n) formula, where all WHERE arguments have been met.
strSQL =
"SELECT FIRST (ROUND(((-(CalcNetWages-tblWageRate.CoefficientB)/(tblWageRate.CoefficientA-1))-CalcNetWages))) " & _
"FROM tblWageType INNER JOIN tblWageRate " & _
"ON tblWageType.WageTypeID = tblWageRate.fk_WageTypeID " & _
"WHERE tblWageRate.TaxYearStart <= CurrentDate And " & _
"tblWageRate.TaxYearEnd >= CurrentDate And " & _
"tblWageType.WageType = CurrWageType And " & _
"tblWageRate.Net >= CalcNetWages;"
CurrentDb.Execute Query:=strSQL, Options:=dbFailOnError + dbSeeChanges
'DoCmd.RunSQL strSQL
End Function
Of course if there is any further questions I'll be around to answer them.
Thanks!
EDIT: Urgh, I've been looking at this code for too long. The ROUND function needed to be encapsulated in brackets. That got rid of error 3075. I have amended my code above to where it is now.
However now I am receiving error 3065 "Cannot execute a select query". With some preliminary Googling it seems that I cannot use a SELECT field in a form, but I don't think that should make a difference as I am calling it in a module. I will attempt further tomorrow as I am off to bed, but in the meantime does anybody have any ideas?
I ended up solving my problem during the week. I believe the problems were a) the way dates were handled and b) missing quotation marks.
This also includes the code that I have that a) called the function in question and b) appended it to a table.
Option Compare Database
Option Explicit
Private Sub btnCalc_Click()
Me.txtWeeklyTax = CalcNetTax(Me.txtWeeklyNet, Me.txtDatePaid, Me.cmbTaxType)
End Sub
Private Sub btnInsertRec_Click()
Dim strSQL As String
strSQL = ""
strSQL = strSQL & "INSERT INTO tblPayment "
strSQL = strSQL & " ( "
strSQL = strSQL & " fk_EmployerID, "
strSQL = strSQL & " fk_EmployeeID, "
strSQL = strSQL & " PaymentDate , "
strSQL = strSQL & " fk_WageTypeID, "
strSQL = strSQL & " NetPayment , "
strSQL = strSQL & " TaxPayable "
strSQL = strSQL & " ) "
strSQL = strSQL & "VALUES "
strSQL = strSQL & " ( "
strSQL = strSQL & " '" & Me.cmbEmployer & "', "
strSQL = strSQL & " '" & Me.cmbEmployee & "', "
strSQL = strSQL & " '" & Me.txtDatePaid & "', "
strSQL = strSQL & " '" & Me.cmbTaxType & "', "
strSQL = strSQL & " '" & Me.txtPropNet & "', "
strSQL = strSQL & " '" & Me.txtPropTax & "' "
strSQL = strSQL & ");"
'strSQL = strSQL & "VALUES "
'strSQL = strSQL & " ( "
'strSQL = strSQL & " '" & Me.[cmbEmployer] & "', "
'strSQL = strSQL & " '" & Me.[cmbEmployee] & "', "
'strSQL = strSQL & " '" & Me.[txtDatePaid] & "', "
'strSQL = strSQL & " '" & Me.[cmbTaxType] & "', "
'strSQL = strSQL & " '" & Me.[txtPropNet] & "', "
'strSQL = strSQL & " '" & Me.[txtPropTax] & "', "
'strSQL = strSQL & ");"
Debug.Print strSQL
DoCmd.RunSQL (strSQL)
Call cmdReset_Click
End Sub
Private Sub cmbEmployer_AfterUpdate()
Me.cmbEmployee.Requery
End Sub
Private Sub cmdReset_Click()
On Error GoTo ResetError
Dim Frm As Form, Ctl As Control
Set Frm = Me
For Each Ctl In Frm
Ctl.Value = Null
Next Ctl
ResetError:
If Err = 2119 Or Err = 438 Or Err = 2448 Then
Resume Next
ElseIf Err > 0 Then
MsgBox Err & ": " & Err.Description
End If
End Sub
Actual tax function...
Option Compare Database
Option Explicit
Public Function CalcNetTax(NetPay As Currency, PayDate As Date, TaxType As Integer) As Currency
Dim db As DAO.Database
Dim rs As DAO.Recordset
Dim strSQL As String
Set db = CurrentDb
strSQL = ""
strSQL = strSQL & "SELECT FIRST (ROUND((-(" & [NetPay] & "-tblWageRate.[CoefficientB])/(tblWageRate.[CoefficientA]-1)-" & [NetPay] & "))) AS TaxPayable "
strSQL = strSQL & "FROM tblWageType "
strSQL = strSQL & " INNER JOIN tblWageRate "
strSQL = strSQL & " ON tblWageType.[WageTypeID] = tblWageRate.[fk_WageTypeID] "
strSQL = strSQL & "WHERE ( "
strSQL = strSQL & " ( "
strSQL = strSQL & " ( "
strSQL = strSQL & " tblWageRate.[TaxYearStart] "
strSQL = strSQL & " ) "
strSQL = strSQL & " <= " & SQLDate([PayDate]) & " "
strSQL = strSQL & " ) "
strSQL = strSQL & " AND "
strSQL = strSQL & " ( "
strSQL = strSQL & " ( "
strSQL = strSQL & " tblWageRate.[TaxYearEnd] "
strSQL = strSQL & " ) "
strSQL = strSQL & " >= " & SQLDate([PayDate]) & " "
strSQL = strSQL & " ) "
strSQL = strSQL & " AND "
strSQL = strSQL & " ( "
strSQL = strSQL & " ( "
strSQL = strSQL & " tblWageType.[WageTypeID] "
strSQL = strSQL & " ) "
strSQL = strSQL & " = " & [TaxType] & " "
strSQL = strSQL & " ) "
strSQL = strSQL & " AND "
strSQL = strSQL & " ( "
strSQL = strSQL & " ( "
strSQL = strSQL & " tblWageRate.[Net] "
strSQL = strSQL & " ) "
strSQL = strSQL & " >= " & [NetPay] & " "
strSQL = strSQL & " ) "
strSQL = strSQL & " );"
Debug.Print strSQL
Set rs = db.OpenRecordset(strSQL)
rs.MoveFirst
CalcNetTax = CCur(rs.Fields(0))
rs.Close
db.Close
Set rs = Nothing
Set db = Nothing
End Function
Private Function SQLDate(vDate As Variant) As String
If IsDate(vDate) Then
SQLDate = "#" & Format$(vDate, "mm\/dd\/yyyy") & "#"
End If
End Function
I have problem with this UPDATE query , I have got message about syntax error query. I think that this query is correct and I can't find what is giving this error.
Link to error
Private Sub cmdModifyBook_Click() 'approves modifying books to the database
Dim str As String
Dim dbs As DAO.Database
Set dbs = CurrentDb()
'checks if the typed all the data of book
If (Me.txtModifyTitle.Value = "") Or (Me.txtModifyTitleWeb.Value = "") Or (Me.txtModifyVerkaufpreis.Value = "") _
Or (Me.txtModifyThemengruppe.Value = "") Then
MsgBox "Nicht alle von Ihnen eingegebenen Daten"
Exit Sub
End If
str = " UPDATE Katalog " _
& "(Bezeichnung, BezeichnungWeb, Verkaufspreis, Themengruppe) SET " _
& "('" & Me.txtModifyTitle.Value & "', '" & Me.txtModifyTitleWeb.Value & "', '" & Me.txtModifyVerkaufpreis.Value & "', '" & Me.txtModifyThemengruppe.Value & "') WHERE ID_Buch =" & Me.lblModifyID.Caption & ";"
dbs.Execute str, dbFailOnError
MsgBox "Das Buch wurde in der Datenbank geändert", vbInformation
dbs.Close
Set dbs = Nothing
End Sub
Your code should look like this instead:
Private Sub cmdModifyBook_Click() 'approves modifying books to the database
Dim str As String
Dim dbs As DAO.Database
Set dbs = CurrentDb()
'checks if the typed all the data of book
If (Me.txtModifyTitle.Value = "") Or (Me.txtModifyTitleWeb.Value = "") Or (Me.txtModifyVerkaufpreis.Value = "") _
Or (Me.txtModifyThemengruppe.Value = "") Then
MsgBox "Nicht alle von Ihnen eingegebenen Daten"
Exit Sub
End If
str = "UPDATE Katalog " & _
"SET Bezeichnung = '" & PQ(Me.txtModifyTitle.Value) & "', " & _
"BezeichnungWeb = '" & PQ(Me.txtModifyTitleWeb.Value) & "', " & _
"Verkaufspreis = '" & PQ(Me.txtModifyVerkaufpreis.Value) & "', " & _
"Themengruppe = '" & PQ(Me.txtModifyThemengruppe.Value) & "' " & _
"WHERE ID_Buch = " & Me.lblModifyID.Caption & ";"
Debug.Print str
MsgBox str
dbs.Execute str, dbFailOnError
MsgBox "Das Buch wurde in der Datenbank geändert", vbInformation
dbs.Close
Set dbs = Nothing
End Sub
Private Function PQ(s as string) as String
PQ = Replace(s, "'", "''")
End Function
Be aware that you need to replace any single quotes that might exist inside the values from the textboxes with two single quotes to prevent SQL errors. That's why I posted the PQ function.
The UPDATE command syntax is as follows
UPDATE Katalog
SET
Bezeichnung = Me.txtModifyTitle.Value ,
BezeichnungWeb = Me.txtModifyTitleWeb.Value ,
Verkaufspreis = Me.txtModifyVerkaufpreis.Value,
Themengruppe = Me.txtModifyThemengruppe.Value
WHERE ID_Buch = Me.lblModifyID.Caption
Of course the above will now work since you have to adopt it for str variable