I searched how to solve my issue in many post but can't find an asnwer.
I need to perform a select in sql where one of the criteria is a date that is between other two dates.
My problem is that my date field in the database is a text area and i need a date to work with
If i run my sql sentence with the date writen it works, but there's a problem when i use variables, here i show the code used.
Thanks in advance
Dim fechaM As Date
Dim fechaAnt As String
Dim fechaPost As String
fechaM = Format(CDate(Nz(rs!fecha_m)), "dd/mm/yyyy")
fechaAnt = Format(CDate(Nz(rs!fecha_m)) - 7, "dd/mm/yyyy")
fechaPost = Format(CDate(Nz(rs!fecha_m)) + 7, "dd/mm/yyyy")
Set rsAguas = Db.OpenRecordset("SELECT table_user.nombre FROM table_user INNER JOIN M_A ON " & _
"table_user.localizacion = M_A.localizacion WHERE " & _
" fechaM " Between " & fechaAnt & " AND " & fechaPost & " " & _
" AND ((M_A.estado)=1)")
When i run this code i don't get error, but it doesn't retrieve data
The bast way to deal with International Dates in Access is to use Allen browne SQLDate Function Allen browne site .
the function
Function SQLDate(varDate As Variant) As String
'Purpose: Return a delimited string in the date format used natively by JET SQL.
'Argument: A date/time value.
'Note: Returns just the date format if the argument has no time component,
' or a date/time format if it does.
'Author: Allen Browne. allen#allenbrowne.com, June 2006.
If IsDate(varDate) Then
If DateValue(varDate) = varDate Then
SQLDate = Format$(varDate, "\#mm\/dd\/yyyy\#")
Else
SQLDate = Format$(varDate, "\#mm\/dd\/yyyy hh\:nn\:ss\#")
End If
End If
End Function
You can use the inbuilt DateValue and DateAdd functions:
WHERE
(M_A.estado = 1) AND
DateValue(fechaM) Between DateAdd("d", -7, DateValue(fechaM)) AND DateAdd("d", 7, DateValue(fechaM))
You are mixing it a little. Try:
Dim fechaM As Date
Dim fechaAnt As String
Dim fechaPost As String
fechaM = Nz(CVDate(rs!fecha_m.Value), Date)
fechaAnt = Format(DateAdd("d", -7, fechaM), "yyyy\/mm\/dd")
fechaPost = Format(DateAdd("d", 7, fechaM), "yyyy\/mm\/dd")
Set rsAguas = Db.OpenRecordset("SELECT table_user.nombre FROM table_user INNER JOIN M_A ON " & _
"table_user.localizacion = M_A.localizacion WHERE " & _
"(fechaMfield Between #" & fechaAnt & "# AND #" & fechaPost & "#) " & _
"AND (M_A.estado = 1)")
Here, fechaMfield is the name of your date field of the table.
If fechaMfield is text, use DateValue([fechaMfield]) in the query.
Related
I am trying to list the dates between two given months: a) 1/1/2021; b) 6/1/2021 in format: 01.2021; 02.2021; 03.2021; 04.2021; 05.2021; 06.2021
I was able to find and use this UDF:
Function MONTHRANGE(startDate As Date, endDate As Date, _
Optional Delim As String = "; ", _
Optional dFormat As String = "MM.YYYY") As String
MONTHRANGE = Join(Evaluate("TRANSPOSE(TEXT(ROW(" & CLng(startDate) & ":" & CLng(endDate) & ")," & Chr(34) & dFormat & Chr(34) & "))"), Delim)
End Function
The output of this is repeated dates (for each day of the month) in the format I want - how can I return just the unique values (one - per month)?
Something like the following gets the job done:
Option Explicit
Private Sub Test()
Debug.Print GetMonths(CDate("1/1/2021"), CDate("6/1/2021"))
End Sub
Private Function GetMonths(ByVal StartDate As Date, ByVal EndDate As Date) As String
Do While StartDate <= EndDate
GetMonths = GetMonths & Format(Month(StartDate), "00") & "." & Year(StartDate) & "; "
StartDate = DateAdd("m", 1, StartDate)
Loop
GetMonths = Left(GetMonths, Len(GetMonths) - 2)
End Function
This is my code below. I am trying to search a database using two different dates, company name
I am getting an error when one of the date fields is empty or null. How can I solve this issue or bypass if the date search field is empty to ignore it in the search or search for an empty field?
Dim SQL As String
SQL = "SELECT * from qryRequestInternal where ([DateRequestSent] = #" & txt_Search_Sdate & "# AND [DateReceived] = #" & txt_Search_Rdate & "# AND (companyName like ""*" & txt_SCompNa & "*"") )"
Me.sfrmRequestInternal.Form.RecordSource = SQL
Me.sfrmRequestInternal.Form.Requery
Me.sfrmRequestInternal_col.Form.RecordSource = SQL
Me.sfrmRequestInternal_col.Form.Requery
End Sub
You will need to check for Null values and build the SQL string based on the controls which have a value (i.e. not null).
The example below uses a helper function to build the sql string. If nothing is inserted, it will only run the the Select * from qryRequestInternal without any criteria.
Private Function SqlWhere() As String
Dim retvalue As String
'sent date
With txt_Search_Sdate
If Not IsNull(.Value) Then
retvalue = " WHERE [DateRequestSent] = #" & Format(.Value, "mm/dd/yyyy") & "#"
End If
End With
'received date
With txt_Search_Rdate
If Not IsNull(.Value) Then
retvalue = IIf(Len(retvalue) = 0, " WHERE", retvalue & " AND") & " [DateReceived] = #" & Format(.Value, "mm/dd/yyyy") & "#"
End If
End With
'company
With txt_SCompNa
If Not IsNull(.Value) Then
retvalue = IIf(Len(retvalue) = 0, " WHERE", retvalue & " AND") & " [companyName] Like '*" & .Value & "*'"
End If
End With
SqlWhere = retvalue
End Function
To call it:
Dim sqlString As String
sqlString = "SELECT * from qryRequestInternal" & SqlWhere()
Debug.Print sqlString
I want to execute a query with a date filter in Access VBA.
My first issue was inconsistent datatypes: expected DATE got NUMBER.
I assume Access stores dates as numbers just like Excel.
I found I had to use "#" between the date for the query to recognize it as a DATE. Now I am getting an INVALID CHARACTER error which means the hash # is an invalid character.
I have to pull in the negotiated costs with our vendors that don't have more than 60 days of being expired.
There is also a tblVendors where the user selects the vendor ID (ORDID) they want to pull the info from. That's why I do a loop to pull in every ORDID in that table. I don't push in all the ORDID in one try because it brings a lot of data and doing it in batches runs faster.
Sub GetMaterialCost()
Dim db As Database
Dim rsData As ADODB.Recordset, rsVendor As DAO.Recordset, rsItemCost As DAO.Recordset
Dim strQuery As String
Dim vendorNO As Long, dtDate As Date
Set db = CurrentDb
dtDate = Format(Now() - 60, "m/d/yyyy")
Set rsVendor = db.OpenRecordset("SELECT ORDID, VEN_NAME, USER_ID FROM tblVendors WHERE ACTIVE = TRUE ORDER BY VEN_NAME, ORDID")
Set rsItemCost = db.OpenRecordset("tbl_ItemCost")
ConnectBILL
rsVendor.MoveFirst
Do Until rsVendor.EOF
strQuery = "SELECT MASID, LOCATION, ITEM, ITEM_QTY, ITEM_UOM, ITEM_COST, EXP_DT " _
& "FROM ITEMMASTER INNER JOIN ORDDETAIL ON (ITEMMASTER.ITEM = ORDDETAIL.ITEM) " _
& "WHERE (LOCATION IN (AS1,AS3,AS6) AND TRIM(MASID) = '" & Cstr(rsVendor.Fields("ORDID")) & "' AND EXP_DT >= #paramDate)"
With ComBill
.CommandText = strQuery
Set rsData = .Execute(, Array(dtDate))
end with
'clears previous instance of vendor data by vendor_no if it exists
db.Execute "DELETE * FROM tbl_ItemCost WHERE MASID LIKE '*" & rsVendor.Fields("ORDID") & "*'"
'starts inserting queried data
rsData.MoveFirst
Do Until rsData.EOF
With rsItemCost
.AddNew
.Fields("MASID") = rsData!MASID
.Fields("LOCATION") = rsData!LOCATION
.Fields("ITEM") = rsData!ITEM
.Fields("ITEM_UOM") = Trim(rsData!ITEM_UOM)
.Fields("ITEM_COST") = rsData!ITEM_COST
.Fields("EXP_DT") = rsData!EXP_DT
.Update
End With
rsData.MoveNext
Loop
rsVendor.MoveNext
Loop
End Sub
Correct these two lines:
dtDate = DateAdd("d", -60, Date)
& "WHERE LOCATION IN (AS1,AS3,AS6) AND TRIM(MASID) = '" & CStr(rsVendor.Fields("ORDID") & "' AND EXP_DT >= #" & Format(dtDate, "yyyy\/mm\/dd") & "#) "
Note, that for ADO, string expressions for date values must be formatted using the ISO sequence.
If the field EXP_DT is Text:
& "WHERE LOCATION IN (AS1,AS3,AS6) AND TRIM(MASID) = '" & CStr(rsVendor.Fields("ORDID") & "' AND EXP_DT >= '" & Format(dtDate, "m\/d\/yyyy") & "') "
I need to get a popup box to appear asking the user to input a date. I want to ensure only dates in the DD/MM/YYYY format can be uploaded.
The below code works, however it allows for any input type to be inserted:
Call RunSQL("UPDATE Summary " & _
"SET " & _
"Date_of_Report = [Enter the Report date in the following format DD/MM/YYYY, with the DD being the last day of the month] " & _
" WHERE Date_of_Report IS NULL ")
I also want to include the name of the file that is being updated in the prompt I tried do the following (where FileNameSelected is a variable that will contain a different value each time), but get an error:
Call RunSQL("UPDATE Summary " & _
"SET " & _
"Date_of_Report = [Enter the Report date for the '" & FileNameSelected & "' file in the following format DD/MM/YYYY, with the DD beng the last day of the month] " & _
" WHERE Date_of_Report IS NULL ")
I would really appreciate if anyone could tell me how to set parameters around the format and also include the value of the FileNameSelected variable in the prompt.
Also for VBA popup boxes I know you use & vbCrLf & _ to create a new line for he message box, how do I do this with a prompt?
That's how I would validate your date. It would be a lot easier with MM/DD/YYYY format. With DD/MM you have to entirely deal with it or you have a risk that Access mixes months and days.
Public Sub Test_date_prompt()
Dim strInpput As String
Dim dtConverted As Date
Dim OK As Boolean
Dim FileNameSelected As String
On Error GoTo Err_handler
OK = False
FileNameSelected = "Anything for this example"
strinput = InputBox("Enter the Report date for the '" & FileNameSelected & "' file in the following format DD/MM/YYYY, with the DD being the last day of the month", "Enter date")
' testing if user inputed 10 characters
If Len(strinput) = 10 Then
' testing if / separators are at the right place
If Mid(strinput, 3, 1) = "/" And Mid(strinput, 6, 1) = "/" Then
' testing if DD, MM, YYYY placeholders are all numeric
If IsNumeric(Left(strinput, 2)) And IsNumeric(Mid(strinput, 4, 2)) And IsNumeric(Right(strinput, 4)) Then
'looks good
OK = True
End If
End If
End If
If Not OK Then
' not good, abording process
MsgBox "You have not entered a valid date in DD/MM/YYYY format !", vbExclamation, "Abording"
GoTo Exit_Sub
End If
' Converting in date which ensure a valid date, otherwise an error will occur
dtConverted = DateSerial(Right(strinput, 4), Mid(strinput, 4, 2), Left(strinput, 2))
' if your Date_of_report type is DATE, do :
' Call RunSQL("UPDATE Summary " & _
"SET " & _
"Date_of_Report = #" & Format(dtConverted, "MM/DD/YYYY") & "# " & _
" WHERE Date_of_Report IS NULL ")
' if your Date_of_report type is STRING (bad!), do :
' Call RunSQL("UPDATE Summary " & _
"SET " & _
"Date_of_Report = '" & Format(dtConverted, "DD/MM/YYYY") & "' " & _
" WHERE Date_of_Report IS NULL ")
Exit_Sub:
Exit Sub
Err_handler:
MsgBox Err.Description
Resume Exit_Sub
End Sub
I prepared the tool, which is downloading email attachments based on user restrictions. Its working well, but when I was implementing it into new person from other dep I had a weird problem, becouse restrict functionality is not working at all. I provide the mailbox, the folder and with restrict details as below and it returns 0, when I checking each email thru loop its see all of them.
Set olApp = CreateObject("Outlook.Application")
Set olNamespace = olApp.GetNamespace("MAPI")
Set olMailboxFolder = olNamespace.Folders("FolderA").Folders("FolderB")
strRestriction = "[ReceivedTime] > '" & Format(myStartDate, "DDDDD HH:MM") & "' AND [ReceivedTime] < '" & Format(myEndDate, "DDDDD" & " 23:59") & "'"
Set olEmailFound = olMailboxFolder.Items.Restrict(strRestriction)
It could be something with outlook/folders setup? If code would be wrong it wont work anywhere, but its only one person...
You must use proper formatting of the date value string expressions:
Not working:
strRestriction = "[ReceivedTime] >= #" & Format(myStartDate, "yyyy\/mm\/dd hh\:nn") & "# AND [ReceivedTime] < #" & Format(DateAdd("d", 1, myEndDate), "yyyy\/mm\/dd") & "#"
Working:
Doc reference: Items.Restrict method (Outlook)
Although dates and times are typically stored with a Date format, the
Find and Restrict methods require that the date and time be converted
to a string representation. To make sure that the date is formatted as
Microsoft Outlook expects, use the Format function.
However, the documentation is buggy. The AM/PM part misses the slash:
sFilter = "[LastModificationTime] > '" & Format("1/15/99 3:30pm", "ddddd h:nn AMPM") & "'"
What seems to work in an International environment, is the predefined formats. Thus, this works with a Danish localisation:
Dim StartDate As String
Dim EndDate As String
Dim n As Integer
StartDate = Format(myStartDate, "Short Date") & " " & Format(myStartDate, "Short Time")
EndDate = Format(myEndDate, "Short Date") & " " & Format(myEndDate, "Short Time")
strRestriction = "[ReceivedTime] >= '" & StartDate & "' And [ReceivedTime] < '" & EndDate & "'"
Debug.Print strRestriction
Debug.Print olMailboxfolder.Items.Count
Set olEmailFound = olMailboxfolder.Items.Restrict(strRestriction)
For n = 1 To olEmailFound.Count
Debug.Print n, olEmailFound.Item(n).ReceivedTime
Next
Note, that if seconds is included in the formatted strings, the comparison will fail.