I have a log function,
We pass in the log name and a message and we open the file and append a text to the end of it.
for some reason, the hour format isn't getting logged correctly, any ideas?
It is logging the correct date but the time is being logged as 00:00:00
Public Shared Sub WriteLog(filename As String, detailToLog As String)
Dim logPath As String = String.Format(Application.StartupPath & "\logs\")
Dim filePath As String = String.Format(logPath & filename & " - {0}.txt", DateTime.Today.ToString("dd-MM-yyyy"))
If (Not System.IO.Directory.Exists(logPath)) Then
System.IO.Directory.CreateDirectory(logPath)
End If
Select Case filename
Case "Error"
File.AppendAllText(filePath, String.Format(DateTime.Today.ToString("dd-MM-yyyy HH:mm:ss") & " Error: " & detailToLog & vbNewLine))
Case "Email"
File.AppendAllText(filePath, String.Format(DateTime.Today.ToString("dd-MM-yyyy HH:mm:ss") & " Email sent to: " & detailToLog & vbNewLine))
Case "Login"
File.AppendAllText(filePath, String.Format(DateTime.Today.ToString("dd-MM-yyyy HH:mm:ss") & " User logged in: " & detailToLog & vbNewLine))
Case "FacialRecognition"
File.AppendAllText(filePath, String.Format(DateTime.Today.ToString("dd-MM-yyyy HH:mm:ss") & " User Identified: " & detailToLog & vbNewLine))
Case "SQL"
File.AppendAllText(filePath, String.Format(DateTime.Today.ToString("dd-MM-yyyy HH:mm:ss") & " SQL query : " & detailToLog & vbNewLine))
End Select
End Sub
The issue is that you are using DateTime.Today. That is specifically the current date with the time zeroed. What you should be using is DateTime.Now, which is the current date AND time. The implementation of DateTime.Today actually returns DateTime.Now.Date.
Exactly as jmcilhinney said, .Today returns only a date, where on .Now returns DateAndTime, you can also get DateAndTime in ISO format YYYYMMDDHHMMSS using Now.ToUniversalTime()
Related
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 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 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.
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.
I have been trying to create a search that pulls up all of the records with a user specified date that falls between the start and end dates of that record. I also want to user to be able to pull it up by "Property" unless they leave it blank.
I am very new to VBA as in started yesterday and this is the latest version that I could come up with:
Private Sub Command4_Click()
Dim strFilter As String
strFilter = [Start_Date] <= Format(Me.RateDate, "Short Date") _
And [End_Date] >= Format(Me.RateDate, "Short Date")
If Not IsNull(Me.Property) Then
strFilter = strFilter & " AND [Num_Code] = '" & Me.Property & "'"
End If
DoCmd.OpenReport "rpt_RatesAll", acViewPreview, , strFilter
End Sub
The most recent error message returns: Run-time error '2465': Microsoft Access can't find '|1' referred to in your expression.
Any help would be very appreciated!
strFilter = "[Start_Date] <= #" Me.RateDate & "# And [End_Date] >= #" & Me.RateDate & "#"
Should do it.
What you had is being taken as a literal string and not using the values you desired.