Dlookup retrieves a date wrong - ms-access

I'm trying to get a date in my database but when the day is less than 12, the month and the day are switched
Example: In the database 2012-02-10 (2 october 2012), the value I get when I do that:
lastDateMill = Nz(DLookup("LastContactDate", "Mills", "MillID = " & lstMills.Column(0, i)), 0)
is
lastDateMill = "10/02/2012"
So I thought that was only a format thing but when I do
Format(lastDateMill, "Long Date")
it equals "February-10-12"
This is how I update the date
DoCmd.RunSQL "UPDATE Mills SET LastContactDate = #" & SalesCallDate & "# WHERE MillID = " & lstMills.Column(0, i)
And the SalesCallDate = "2/10/2012" so the good date
So why the day and the month are switched?
The front end is ms-access-2010 and the back end is on SQL SERVER 2012

Your SalesCallDate variable contains a date as text:
SalesCallDate = "2/10/2012"
Apparently you intend the date format of that string to be m/d/yyyy, but it gets interpreted as d/m/yyyy format.
Store the string value in yyyy/mm/dd format to eliminate confusion due to locale issues ... 2012/02/10
Since it turns out that SalesCallDate is actually a text box containing a date value, change your UPDATE approach to avoid date problems due to locale.
Dim strUpdate As String
Dim db As DAO.Database
strUpdate = "UPDATE Mills SET LastContactDate = " & _
Format(Me.SalesCallDate, "\#yyyy-m-d\#") & vbCrLf & _
"WHERE MillID = " & Me.lstMills.Column(0, i)
Debug.Print strUpdate
Set db = CurrentDb
db.Execute strUpdate, dbFailonerror
Set db = Nothing

Try this, by explicitly specifying a format
DoCmd.RunSQL "UPDATE Mills SET LastContactDate = #" & _
Format$(SalesCallDate,"yyyy/mm/dd") & "# WHERE MillID = " & _
lstMills.Column(0, i)
UPDATE:
Maybe there is better way to do it, that is independent of any formattings. The idea is to tranfer the date from table to table, without any combo-, list- or text in between. Therefore any conversion from a date type to string and then back to a date field is avoided.
If the tables can be joined (assuming that MillID is the bound field of the listbox):
DoCmd.RunSQL "UPDATE Mills " & _
"INNER JOIN sourceTable ON Mills.MillID = sourceTable.MillID " & _
"SET LastContactDate = sourceTable.SalesCallDate " & _
"WHERE Mills.MillID = " & lstMills
Otherwise
DoCmd.RunSQL "UPDATE Mills SET LastContactDate = " & _
"(SELECT SalesCallDate FROM sourceTable WHERE ID = " & sourceID & ")" _
"WHERE Mills.MillID = " & lstMills

Related

Use text from record to paste into an Access form controlbox

Based on a user's job ID number, I create a recordset of an ID with its different unit types (think pipe sizes) and unit (think footage of pipe). Each unit type record already has the name of the form textbox where the total footage goes in a different column. What I want to do is go through each recordset and plugin the footage for each unit type for that job ID number (that the user puts in a form).
Dim rst_UnitEntryCounts As Recordset
Set rst_UnitEntryCounts = CurrentDb.OpenRecordset("SELECT tbl_UnitTypes.UnitTypes_WeeklyTextBoxUserEntryForm, " _
& " tbl_PMEntry.PMEntry_Week_Ending, " _
& " tbl_UnitTypes.UnitTypes_CumalativeTextBoxUserEntryForm, " _
& " Sum(tbl_UnitEntry.UnitEntry_Unit_Count) AS SumOfUnitEntry_Unit_Count " _
& "FROM tbl_UnitTypes " _
& " INNER JOIN tbl_UnitEntry ON tbl_UnitTypes.UnitTypes_ID = tbl_UnitEntry.UnitEntry_UnitTypes_ID) " _
& " INNER JOIN (tbl_PMHeader " _
& " INNER JOIN tbl_PMEntry ON tbl_PMHeader.PMHeader_ID = tbl_PMEntry.PMEntry_PMHeader_ID) ON tbl_UnitEntry.UnitEntry_PMEntry_ID = tbl_PMEntry.PMEntry_PMHeader_ID " _
& "WHERE tbl_PMHeader.PMHeader_ID = " & num_PM _
& "GROUP BY tbl_UnitTypes.UnitTypes_WeeklyTextBoxUserEntryForm, " _
& " tbl_PMEntry.PMEntry_Week_Ending, " _
& " tbl_UnitTypes.UnitTypes_CumalativeTextBoxUserEntryForm ")
rst_UnitEntryCounts.MoveFirst
Do Until rst_UnitEntryCounts.EOF = True
[rst_UnitEntryCounts.UnitTypes_WeeklyTextBoxUserEntryForm] = SumOfUnitEntry_Unit_Count
rst_UnitEntryCounts.MoveNext
Loop
Exit Sub
image of what my query table looks like
Also, Im getting an error 3131 Syntax error in FROM clause as well.
Thanks in advance!
Finally figured out how to "place" a value (sum of units) in a textbox that varies based on criteria (unit type) in a form, where the name of the textbox is inside a record itself within my recordset. In case someone else has a similar question, here is how I did it:
Dim cntl As String
Dim frm As String
Dim rst_UnitEntry As Recordset
frm = "frm_UserEntry"
Set rst_UnitEntryCounts = CurrentDb.OpenRecordset("SELECT...)
If rst_UnitEntryCounts.RecordCount <> 0 Then
rst_UnitEntryCounts.MoveFirst
Do Until rst_UnitEntryCounts.EOF = True
If rst_UnitEntryCounts![UnitTypes_CumalativeTextBoxUserEntryForm] <> "" Then
cntl = rst_UnitEntryCounts![UnitTypes_CumalativeTextBoxUserEntryForm]
Forms(frm).Controls(cntl) = rst_UnitEntryCounts![SumOfUnitEntry_Unit_Count]
End If
rst_UnitEntryCounts.MoveNext
Loop

Why doesn't this DAO recordset query return any results?

I am working on an Access 2007 database and I have set up a DAO recordset query, however, it is not returning any results. It does not throw up any errors, just no results. Me.ProID is a text field, it includes letters and numbers. I think it has something to do with the text field, maybe the placement of quotations.
Dim contractSQL As String
Dim contractDB As DAO.Database
Dim contractRS As DAO.Recordset
contractSQL = "SELECT Top 1 ContractName, ItemDescription, Price FROM ContractPricing WHERE AccountNo = " & Me.Parent.[AccntNumber] & " AND PartNo = " & """ & Me.ProdID & """ & " ORDER BY Price Asc"
Set contractDB = CurrentDb
Set contractRS = contractDB.OpenRecordset(contractSQL)
Debug.Print contractRS.RecordCount
That string concatenation is likely wrong. " & """ & Me.ProdID & """ & " should almost certainly be '" & Me.ProdID & "'
I don't know if you're referring to this:
contractSQL = "SELECT Top 1 ContractName, ItemDescription, Price FROM ContractPricing WHERE AccountNo = " & Me.Parent.[AccntNumber] & " AND PartNo = " & Me.ProdID & " ORDER BY Price Asc"
I'm not sure if this would help you. I'm also new to this. But hopefully it will.

VBA issues when trying to run a SQL query between 2 dates

To give a brief summary of the objective of this macro, I am trying to get the sum of cash between certain dates based on a set of parameters. I keep getting an error in VBA when I try to run a SQL query with a date. I'm not sure what the issue is but I think it's related to how I have the date formatted. I have tried running it multiple ways but keep getting a syntax error, whether it be related to 'a', '#', or 'table'.
Here's the query I'm using. Any help would be greatly appreciated.
Sub GetCashBalance()
Dim cn As New ADODB.Connection
Dim rs As ADODB.Recordset
Dim SQL As String
Dim StartDate As String
Dim EndDate As String
StartDate = InputBox("Enter Start Date in mm/dd/yy format.")
EndDate = InputBox("Enter End Date in mm/dd/yy format.")
SQL = "Provider=SQLOLEDB.1;Integrated Security=SSPI;Persist Security Info=True;Initial Catalog=master;Data Source=SERVER\ODS"
Set cn = New ADODB.Connection
Set rs = New ADODB.Recordset
cn.Open SQL
Set rs = cn.Execute("SELECT SUM(a.CASH)" & _
"FROM CUSTOMER_DATA.dbo.TRANSACTION_HISTORY a" & _
"LEFT JOIN CUSTOMER_DATA.dbo.DAILY_TRANSACTION b" & _
"ON a.T01_KEY = b.T01_KEY" & _
"WHERE PROC_DATE BETWEEN #StartDate# AND #EndDate#" & _
"AND a.CODE NOT IN ('22','23','M','2-L','36-R')" & _
"AND isnull(a.DESCRIPTION, '') NOT IN ('01','02','03','0DO1','0NF2');")
If Not rs.EOF Then
Sheets(7).Range("A40").CopyFromRecordset rs
rs.Close
Else
MsgBox "Error", vbCritical
End If
cn.Close
End Sub
Set rs = cn.Execute("SELECT SUM(a.CASH)" & _
"FROM CUSTOMER_DATA.dbo.TRANSACTION_HISTORY a" & _
"LEFT JOIN CUSTOMER_DATA.dbo.DAILY_TRANSACTION b" & _
"ON a.T01_KEY = b.T01_KEY" & _
"WHERE PROC_DATE BETWEEN '" & StartDate & "' AND '" & EndDate & _
"# AND a.CODE NOT IN ('22','23','M','2-L','36-R')" & _
"AND isnull(a.DESCRIPTION, '') NOT IN ('01','02','03','0DO1','0NF2');")
Take a look at below piece, that should be changed
BETWEEN '" & StartDate & "' AND '" & EndDate & _
"' AND ....
I think it is better to use ADODB.Command and Parameters instead of doing a concatenation in the sql query.

VBA Access - Multiple Tables count by date

We'd like to count from an Access database that has multiple tables - about 50.
We need to count from 1 column in each table that is 'QCPASS' This is a check box - if a product passed the box was checked if failed then not. We need to count both for EACH table, also allowing the user to specify a date range from a date column that exists in every table.
I've tried this with a query but I am told the query is unable to select, count and do the date range. Any VBA help would be great.
Exporting to Excel would be great, but any results would be fine. Here is the query I created that counts in a column from each table passes and failures. I can't iterate with a query either, so VBA seems the way to go:
SELECT "Table1" , Count('qcpass') AS column
FROM 5000028
GROUP BY [5000028].qcpass
union
SELECT "Table2",count('qcpass')
FROM 5000029
Group By [5000029].qcpass;
You can traverse the full TableDefs collection in your database, and create a query using VBA.
A word of warning: The TableDefs collection has the Access database system tables, so you need to skip this. A way I suggest you is to check for a specific table name prefix (it is noted in the code below).
public sub createMyBigUnionQuery()
dim db as DAO.database(), tbl as DAO.tableDef
dim strSQL as string, i as integer
set db = currentdb()
i = 1
for each tbl in db.TableDefs
if left(tbl.name, 1) = "5" then ' Check for a table name prefix
if i = 1 then
' The final spaces are important
strSQL = "select '" & tbl.Name & "' as table, count(qcpass) as column " & _
"from [" & tbl.Name & "] " & _
"group by qcpass "
else
' The final spaces are important
strSQL = strSQL & " union all " & _
"select '" & tbl.Name & "' as table, count(qcpass) as column " & _
"from [" & tbl.Name & "] " & _
"group by qcpass "
end if
i = i + 1
end if
next tbl
db.createQueryDef "qryYourFinalQuery", strSQL
db.close
exit sub
Notice that you can define any valid query you want. Take this as a hint, and tweak it to fit your specific needs.
Hope this helps you
Adressing #HansUp comment, if you need to filter your data by date, you have two options:
Include the where condition on every select created by the procedure
Include the date field in your query and group by it, and create a second query to filter the data you need from the created query.
I would personally go with option 1, and here is a sample code:
public sub createMyBigUnionQueryWithDates(d0 as date, d1 as date)
dim db as DAO.database(), tbl as DAO.tableDef
dim strSQL as string, i as integer
set db = currentdb()
i = 1
for each tbl in db.TableDefs
if left(tbl.name, 1) = "5" then ' Check for a table name prefix
if i = 1 then
' The final spaces are important
strSQL = "select '" & tbl.Name & "' as table, count(qcpass) as column " & _
"from [" & tbl.Name & "] " & _
"where rowDate between " & cDbl(d0) & " and " &cDbl(d1) & " " & _
"group by qcpass "
else
' The final spaces are important
strSQL = strSQL & " union all " & _
"select '" & tbl.Name & "' as table, count(qcpass) as column " & _
"from [" & tbl.Name & "] " & _
"where rowDate between " & cDbl(d0) & " and " &cDbl(d1) & " " & _
"group by qcpass "
end if
i = i + 1
end if
next tbl
db.createQueryDef "qryYourOtherFinalQuery", strSQL
db.close
exit sub
The reason I use cDbl(d0) is because Access dates are sensitive to regional settings, and I've had a lot of headaches dealing with it. Access (and many other Microsoft products) store dates as floating-point numbers (the integer part is the date, and the decimal part is the time).
Another word of warning: If your dates don't include time, then the between condition will work. But if they do include time, then I recommend you change the where condition to this:
"where rowDate >= " & cDbl(d0) & " and rowDate < " & cDbl(d1 + 1)"

Invalid Argument Error: MSAccess and SQL

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.