In my Access form I'm getting a
Run-time error'3705:
Syntax error in date query expression '(( ( [Date of Purchase] >=##And[Date of urchase]<=##))'.
whenever I run my code that,without the Me.TxtPurchaseDateTo and Me.TxtPurchaseDateTo
fields being populated instead of the msg box that should run. In addition I get a "Enter Parameter Value" dialog box popping up when I click the "Clear" button with or without data being displayed. In order to clear the form of data I have to hit the space bar while in the input box of the "Enter Parameter Value" dialog box in order to clear the form. If I hit cancel I get a Run-time error 2501 "the ApplyFilter action was canceled and I'm taken to my code sheet with the "DoCmd.ApplyFilter task" highlighted if I debug the error.
I have removed several portions of the code rechecked the spelling and spacing
Option Compare Database
Private Sub CmdSearch_Click()
'Search button
Call Search
End Sub
Sub Search()
Dim strCriteria, task As String
Me.Refresh
If IsNull(Me.TxtPurchaseDateFrom) Or IsNull(Me.TxtPurchaseDateTo) Then
MsgBox "Please enter the date range", vbInformation, "Date Range
Required"
Me.TxtPurchaseDateFrom.SetFocus
Else
strCriteria = "([Date of Purchase] >= #" & Me.TxtPurchaseDateFrom & "#
And [Date of Purchase] <=#" & Me.TxtPurchaseDateTo & "#)"
task = "select * From TblPurchases Where( " & strCriteria & ") order
by [Date of Purchase] "
DoCmd.ApplyFilter task
'Me.TxtTotal = FindRecordCount
End If
End Sub
Private Sub CmdClear_Click()
Dim task As String
Me.TxtPurchaseDateFrom = ""
Me.TxtPurchaseDateTo = ""
task = "select * from TblPurchases where PrimaryKey is null"
DoCmd.ApplyFilter task
'Me.TxtTotal = FindRecordCount
End Sub
Private Sub CmdShowAll_Click()
Dim task As String
Me.TxtPurchaseDateFrom = ""
Me.TxtPurchaseDateTo = ""
task = "select * from TblPurchases order by [Date of Purchase] "
Me.RecordSource = task
'Me.TxtTotal = FindRecordCount
End Sub
I'm expecting that if I just cancel the dialog box the form should remain on screen.
Also if the "from" and "t/o" fields are empty I should get the MsgBox results.
i'm not sure what is the syntax error surrounding the "DoCmd.ApplyFilter task"
What error am I not seeing?
Your criteria cannot be a full SQL sentence, only the criteria:
strCriteria = "[Date of Purchase] >= #" & Me.TxtPurchaseDateFrom & "# And [Date of Purchase] <= #" & Me.TxtPurchaseDateTo & "#"
DoCmd.ApplyFilter strCriteria
You can use Nz to avoid errors from empty textboxes:
strCriteria = "[Date of Purchase] >= #" & Nz(Me!TxtPurchaseDateFrom.Value, Date) & "# And [Date of Purchase] <= #" & Nz(Me!TxtPurchaseDateTo.Value, Date) & "#"
DoCmd.ApplyFilter strCriteria
Or:
If IsNull(Me!TxtPurchaseDateFrom.Value) Then
strCriteria = "[Date of Purchase] <= #" & Nz(Me!TxtPurchaseDateTo.Value, Date) & "#"
Else
strCriteria = "[Date of Purchase] >= #" & Nz(Me!TxtPurchaseDateFrom.Value, Date) & "# And [Date of Purchase] <= #" & Nz(Me!TxtPurchaseDateTo.Value, Date) & "#"
End If
DoCmd.ApplyFilter strCriteria
Related
this is to add records from expenses record to an invoice details table using an invoice input form with sub forms
all related by "inv no"
i am coping info from
Exp_Inv_input_Form
to
sub form = service atlan of main form = atlan inv main
i have been trying to use INSERT INTO with no luck and cant figure out where i am going wrong
Private Sub btn_copy_Click()
Dim strSql As String
Dim IngID As Long
If Me.Dirty Then
Me.Dirty = False
End If
If Me.NewRecord Then
MsgBox "select the record to duplicate."
Else
With Me.RecordsetClone
.AddNew
!description_date = Me.TransactionDate
!description = Me.description
!hours = Me.Quantity
!Price = Me.SubTotal
!Total = Me.SubTotal
.Update
.Bookmark = .LastModified
IngID = !inv_no
If Me.RecordsetClone.RecordCount > 0 Then
strSql = "insert into [service atlan subform]([inv no], [description date], description, hours, Price, Billed )" _
"SELECT " & lngID & " As NewID, description, Quantity, Total, from_exp " & _
"FROM [service atlan] WHERE inv no = " & Me.inv_no & ";"
DBEngine(0)(0).Execute strSql, dbFailOnError
Else
MsgBox "Main record duplicated, but there were no related records."
End If
Exit_Handler:
Exit Sub
Err_Handler:
MsgBox "Error " & Err.Number & " - " & Err.description, , "cmdDupe_Click"
Resume Exit_Handler
End Sub
now its telling me that there is a problem with my strSql
do i need to name the colums the same in both the tables as i was led to belive that its the sequance in which they are placed
thanks in advance
There are few issues with your sql statement. If you have blank space in column name, enclose with [] .
Also number of columns in the insert statement not matching with select statement
Also there is , after the table name in the Insert statement
I Have been messing around with the SLQ changed the table structure a bit and have had success my bigest problem was the structure of the Select statment
"INSERT INTO [Transaction List] ([TransactionDate], [Inv No], [Division], [MomsrevLookup], [Total], [Catagory]) " & _
"Select """ & Me.[TransactionDate].Value & """, """ & Me.[inv no].Value & """,""" & Me.[Division].Value & """,""" & Me.revmoms.Value & """,""" & Me.[Inv_Total].Value & """,""" & Me.[Catagory].Value & """"
it is now coping selected rows from the form and pasting them to new records on another table
I have a report that uses the following SQL query:
SELECT AccountPerformanceAllHistory.AccountNumber,
AccountMaster.AccountName AS Name, AccountCurrentModel.Model,
AccountPerformanceAllHistory.MarketValue,
AccountPerformanceAllHistory.Cash, ModelDetailAllHistory.Risk,
AccountPerformanceAllHistory.QTD, AccountPerformanceAllHistory.YTD,
AccountPerformanceAllHistory.[1Yr], AccountPerformanceAllHistory.[3Yr],
AccountMaster.AccountAdvisor AS Advisor,
AccountPerformanceAllHistory.PerformanceDate,
AccountPerformanceAllHistory.Ticker
FROM ModelDetailAllHistory INNER JOIN ((AccountMaster INNER JOIN
AccountPerformanceAllHistory ON AccountMaster.[AccountNumber] =
AccountPerformanceAllHistory.[AccountNumber]) INNER JOIN
AccountCurrentModel ON AccountMaster.[AccountNumber] = AccountCurrentModel.
[AccountNumber]) ON ModelDetailAllHistory.[ModelName] =
AccountCurrentModel.Model
GROUP BY AccountPerformanceAllHistory.AccountNumber,
AccountMaster.AccountName, AccountCurrentModel.Model,
AccountPerformanceAllHistory.MarketValue,
AccountPerformanceAllHistory.Cash, ModelDetailAllHistory.Risk,
AccountPerformanceAllHistory.QTD, AccountPerformanceAllHistory.YTD,
AccountPerformanceAllHistory.[1Yr], AccountPerformanceAllHistory.[3Yr],
AccountMaster.AccountAdvisor, AccountPerformanceAllHistory.PerformanceDate,
AccountPerformanceAllHistory.Ticker
ORDER BY ModelDetailAllHistory.Risk, AccountPerformanceAllHistory.[1Yr]
DESC;
The report is run from a button-click:
Private Sub Command3_Click()
Dim StrWhichMonth As String
Dim StrWhichClient As String
Dim CYear, CMonth As Variant
Dim StrSearch As String
StrWhichMonth = InputBox("Enter YYMM you want to report:")
CYear = "20" & Mid(StrWhichMonth, 1, 2)
CMonth = Mid(StrWhichMonth, 3, 2)
StrWhichMonth = DateSerial(CYear, CMonth + 1, 0)
StrWhichClient = InputBox("Enter Client name ('*' for all):")
StrSearch = "AccountPerformanceAllHistory.PerformanceDate = #" & StrWhichMonth _
& "# AND AccountPerformanceAllHistory.Ticker = " & Chr(34) & "1" & Chr(34) & "" _
& " AND AccountMaster.AccountName Like " & Chr(34) & StrWhichClient & Chr(34)
StrWhichMonth = "AccountPerformanceAllHistory.PerformanceDate = #" & StrWhichMonth _
& "# AND AccountPerformanceAllHistory.Ticker = " & Chr(34) & "1" & Chr(34) & ""
DoCmd.SetWarnings False
' DoCmd.OpenReport "RPTAccountPerformanceAllHistorySummary", acViewReport, , StrWhichMonth
DoCmd.OpenReport "RPTAccountPerformanceAllHistorySummary", acViewReport, , StrSearch
DoCmd.SetWarnings True
End Sub
As you might can tell, I added the search for AccountName in the button click code. The old code works fine.
The new code, with the StrSearch string does not work. When the query is run, it prompts for "AccountMaster.AccountName" after the two InputBox prompts. I know this means something is wrong with the StrSearch, but I don't know what is wrong. I've searched around the web, but could not find a solution.
Any help is appreciated.
TIA
The field list in your source query includes this one ...
AccountMaster.AccountName AS Name
Since you aliased the field, the query result set does not include a field named AccountMaster.AccountName, so Access assumes it must be a parameter and asks you to supply a value for it. Use the alias instead instead of the original field name.
Change this ...
& " AND AccountMaster.AccountName Like " & Chr(34) & StrWhichClient & Chr(34)
to this ...
& " AND [Name] Like " & Chr(34) & StrWhichClient & Chr(34)
I am at a loss and don't know where else to go to try to get assistance.
Here is what I have put together. Most of this is for the date filtering. If a start date and an end date are entered, the records for that range are supplied. If a start date is entered by no end date, records are pulled from that date forward. If an end date is entered but no start date, all records are pulled up to the end date. If no dates are entered the entire universe is retrieved. The section that I am having trouble with the selected value from a combobox that I have added. The combo box is based off of a query that pulls in each unique id (such as 00001, 00073...) and based on the dates entered and the id selected I want to retrieve and report on just those specific records. The way that it is below returns the data for the unique id selected but the date range is ignored.
I have tried quite a few avenues and I also attempted to add an if statement for Me.Client_List.Value, but I don't know what I am doing wrong with that either. I have to admit I have not been using access for quite a few years and I am feeling lost.
thank you to anyone that can assist me.
-Rick
My combobox name is Client_List and the value to be filtered on is Client ID
attempted If statement:
If Me.Client_List.Value = "Client ID" Then
strWhere = strWhere & "([Client ID] = True) AND"
ElseIf Me.Client_List.Value = "" Then
strWhere = strWhere & "([Client ID] = False) AND "
End If
VBA that works to include the combobox selection on the reportview but the date filters are being ignored:
Private Sub RunReport_2_button_Click()
On Error GoTo Err_Handler
Dim strReport As String
Dim strDateField As String
Dim strWhere As String
Dim lngView As Long
Const strcJetDate = "\#mm\/dd\/yyyy\#"
strReport = "Audits by DOS_Client"
strDateField = "[Date of Service]"
lngView = acViewPreview
If IsDate(Me.dos_start) Then
strWhere = "(" & strDateField & " >= " & Format(Me.dos_start, strcJetDate) & ")"
End If
If IsDate(Me.dos_end) Then
If strWhere <> vbNullString Then
strWhere = strWhere & " AND "
End If
strWhere = strWhere & "(" & strDateField & " < " & Format(Me.dos_end + 1, strcJetDate) & ")"
End If
If CurrentProject.AllReports(strReport).IsLoaded Then
DoCmd.Close acReport, strReport
End If
Debug.Print strWhere
DoCmd.OpenReport "Audits by DOS_Client", acViewPreview, , "[Client Id] = '" & Me.Client_List.Value & "'"
Exit_Handler:
Exit Sub
Err_Handler:
If Err.Number <> 2501 Then
MsgBox "Error " & Err.Number & ": " & Err.Description, vbExclamation, "Cannot open report"
End If
Resume Exit_Handler
End Sub
Well, it could be:
If strWhere <> "" Then
strWhere = strWhere & " AND "
End If
strWhere = strWhere & "[Client Id] = '" & Me.Client_List.Value & "'"
Debug.Print strWhere
DoCmd.OpenReport "Audits by DOS_Client", acViewPreview, , strWhere
I have Access Database table with multiple overlapping schedule. I hought it will be simple for me to create Bu faced with some overlapping existing time range. If an user approves a schedule for one employee. When user goes to approve next schedule with overlapping time for the same employee. I Need to create an alert message when user approves overlapping schedule and delete ‘approved’ text from the table. Not much knowledge about VB code or if there is something I can set up in query. Any help will be appreciated.
OK, I have a table with 3 fields: EmpID, StartTime, & EndTime. The Start & End times have the date & time together.
Then I have a form with the same 3 fields.
In the VBA code, under the Before_Update event, I check to see if there's a conflict, and if so, I set the Cancel property to true and display a message. Here's the code:
Private Sub Form_BeforeUpdate(Cancel As Integer)
Dim RS As Recordset
Dim strSQL As String
Dim EmpID As Long
Dim ScheduleStart As String
Dim ScheduleEnd As String
EmpID = Me.txtEmpID
ScheduleStart = Me.txtStartTime
ScheduleEnd = Me.txtEndTime
strSQL = ""
strSQL = strSQL & "SELECT Count(schedule.EmpID) AS Conflict " & vbCrLf
strSQL = strSQL & "FROM schedule " & vbCrLf
strSQL = strSQL & "WHERE ( ( ( Schedule.EmpID ) = #EmpID ) " & vbCrLf
strSQL = strSQL & " AND ( ( ##ScheduleStart# ) <= [StartTime] ) " & vbCrLf
strSQL = strSQL & " AND ( ( ##ScheduleEnd# ) > [StartTime] ) ) " & vbCrLf
strSQL = strSQL & " OR ( ( ( Schedule.EmpID ) = #EmpID ) " & vbCrLf
strSQL = strSQL & " AND ( ( ##ScheduleStart# ) <= [EndTime] ) " & vbCrLf
strSQL = strSQL & " AND ( ( ##ScheduleEnd# ) > [EndTime] ) )"
strSQL = Replace(strSQL, "#EmpID", EmpID)
strSQL = Replace(strSQL, "#ScheduleStart", ScheduleStart)
strSQL = Replace(strSQL, "#ScheduleEnd", ScheduleEnd)
Debug.Print strSQL
Set RS = CurrentDb.OpenRecordset(strSQL)
If RS("Conflict") > 0 Then
Cancel = True
MsgBox "Conflict Detected", vbExclamation, "Conflict Detected"
End If
End Sub
This looks for 2 scenarios, both using the EmpID.
If the ScheduleStart < StartTime AND ScheduleEnd > StartTime
Or ScheduleStart < EndTime AND ScheduleEnd > EndTime
Most of the code is building the SQL. It would be much neater if a parameter query was used, but I did it this way because I thought it was clearer.
The Debug.Print strSQL will show you what the query your building looks like.
This has no error checking, so you'l have to put some in.
Right now, when you enter dates, it has to look like: 6/26/13 4:31 pm
I created a sample set of data and a form that looks like this:
And I added this bit of code to the conflicts button to see if your StartTime and StartDate fall between the StartTime/StartDate and EndTime/EndDate of any of the other records. You would need to modify the code just a bit to also check that the EndTime and EndDate don't fall between as well.
Private Sub Test_Button_Click()
Dim myR As Recordset
Dim strSQL As String
strSQL = "Select * From Sample Where " & _
"StartDate <= #" & Me.StartDate & "# " & _
"And StartTime <= #" & Me.StartTime & "# " & _
"And EndDate >= #" & Me.StartDate & "# " & _
"And EndTime >= #" & Me.StartTime & "#"
Debug.Print strSQL
Set myR = CurrentDb.OpenRecordset(strSQL, dbOpenDynaset)
If myR.RecordCount = 0 Then
Debug.Print "There are no conflicts"
End If
Set myR = Nothing
End Sub
I am trying to access certain lines from my SQL database from MSAccess and I keep getting an Invalid Argument Error on this line:
Set rs = CurrentDb.OpenRecordset("SELECT TimeID " & _
"FROM tblLunchTime " & _
"WHERE ProductionID = prodSelect AND EndTime is NULL AND StartTime < dateAdd('h', 3, NOW())", [dbSeeChanges])
Is something not right in this?
Private Sub cmdClockEnd_Click()
'Check if a group has been selected.
If frmChoice.value = 0 Then
MsgBox "Please select a production line."
End
End If
'Setup form for user input.
lblEnd.Visible = True
'Save end of lunch value.
lblEnd.Caption = Format(Now, "MMM/DD/YY hh:mm:ss AMPM")
'Declare database variables.
Dim dbName As DAO.Database
Dim strValuesQuery As String
Dim rs As DAO.Recordset
Dim prodSelect As String
Dim sSQL As String
Dim timeValue As String
Set dbName = CurrentDb
'Get values of Production Line.
If frmChoice.value = 1 Then
prodSelect = "L2"
ElseIf frmChoice.value = 2 Then
prodSelect = "L3"
End If
'Get the last TimeID with the following parameters.
sSQL = "SELECT TimeID " & _
"FROM tblLunchTime " & _
"WHERE ProductionID = prodSelect AND EndTime is NULL AND StartTime < #" & DateAdd("h", 3, Now()) & "#"
Set rs = dbName.OpenRecordset(sSQL, dbSeeChanges)
strValuesQuery = _
"UPDATE tblLunchTime " & _
"SET EndTime = '" & Now & "'" & _
"WHERE TimeID = " & rs![TimeID] & " "
'Turn warning messages off.
DoCmd.SetWarnings False
'Execute Query.
DoCmd.RunSQL strValuesQuery
'Turn warning messages back on.
DoCmd.SetWarnings True
End Sub
You need to put prodSelect outside the quotes:
"WHERE ProductionID = " & prodSelect & " AND ...
It is nearly always best to say:
sSQL="SELECT TimeID " & _
"FROM tblLunchTime " & _
"WHERE ProductionID = " & prodSelect & _
" AND EndTime is NULL AND StartTime < dateAdd('h', 3, NOW())"
''Debug.print sSQL
Set rs = CurrentDb.OpenRecordset(sSQL)
You can see the advantage in the use of Debug.Print.
AHA prodSelect is text! You need quotes!
sSQL="SELECT TimeID " & _
"FROM tblLunchTime " & _
"WHERE ProductionID = '" & prodSelect & _
"' AND EndTime is NULL AND StartTime < dateAdd('h', 3, NOW())"
There appears to be confusion about tblLunchTime ... whether it is a native Jet/ACE table or a link to a table in another database. Please show us the output from this command:
Debug.Print CurrentDb.TableDefs("tblLunchTime").Connect
You can paste that line into the Immediate Window and press the enter key to display the response. (You can open the Immediate Window with CTRL+g keystroke combination.)
Just in case the response starts with "ODBC", suggest you try this line in your code:
Set rs = CurrentDb.OpenRecordset(sSQL, dbOpenDynaset, dbSeeChanges)
Update: Now that you're past that hurdle, suggest you change your approach with the UPDATE statement. Don't turn off warnings; try something like this instead:
'Execute Query. '
CurrentDb.Execute strValuesQuery, dbFailOnError
And add an error handler to deal with any errors captured by dbFailOnError.
I think I would do the date criterion concatenation client-side, too, since it's one more thing that could go wrong:
"...StartTime < #" & DateAdd("h", 3, Now()) & "#"
I don't know that SQL Server doesn't have DateAdd() and Now() function nor that they don't behave exactly the same as in Access, but I wouldn't take the chance -- I'd do this calculation on the client instead of handing it off to the server.