Set column value to user input, limit to date format - vba

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

Related

Searching for data in a combo list

I have a database with a table ALL_INCOME which contains all my data with reference to income.
I managed to create a search button which is able to search the data in a date range successfully.
My table has these fields:
Date,Type of income, Amount.
I will like to search in a date range so it can pick a specific type of income records to be displayed.
For instance, if I have investment, savings as the type of income in my table and also in my combo list, I will like to be able to search in a date range using a specific type of income.
These are my codes which is able to search data in a date range that displays all data.
Private Sub Command20_Click()
' Search button
Call Search
End Sub
Sub Search()
Dim strCriteria, task As String
Me.Refresh
If IsNull(Me.OrderDateFrom) Or IsNull(Me.OrderDateTo) Then
MsgBox "Please enter the date range", vbInformation, "Date Range Required"
Me.OrderDateFrom.SetFocus
Else
strCriteria = "([DATE] >= #" & Me.OrderDateFrom & "# And [DATE] <= #" & Me.OrderDateTo & "#)"
task = "select * from ALL_INCOME where (" & strCriteria & ") order by [DATE]"
DoCmd.ApplyFilter task
End If
End Sub
Any help with this will be greatly appreciated.
Thank you
Try below codes. It will search specific IncomeType between two date range. If you do not select any IncomeType then it will filter all IncomeType in specified date range.
Option Compare Database
Option Explicit
Private Sub cmdApplyFilter_Click()
Call Search
End Sub
Sub Search()
Dim strCriteria, task As String
Me.Refresh
If IsNull(Me.OrderDateFrom) Or IsNull(Me.OrderDateTo) Then
MsgBox "Please enter the date range", vbInformation, "Date Range Required"
Me.OrderDateFrom.SetFocus
Else
strCriteria = "[MyDate] >= " & Format(Me.OrderDateFrom, "\#mm\/dd\/yyyy\#") & _
" And [MyDate] <= " & Format(Me.OrderDateTo, "\#mm\/dd\/yyyy\#") & _
" AND [IncomeType] LIKE '" & IIf(IsNull(Me.cboIncomeType), "*", Me.cboIncomeType) & "'"
'task = "select * from ALL_INCOME where (" & strCriteria & ") order by [DATE]"
DoCmd.ApplyFilter , strCriteria
End If
End Sub

date time format issue in .net hours like 00:00:00

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()

Access vba sql query with date in format dd/mm/yyyy

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.

Date displays in msgbox but not a variable to rename a worksheet

I am trying to rename a worksheet tab with last Saturday's date. I can get the date to display properly using a Msgbox.
However when I try to use the same variable in the code, it throws a "Compile error: Expected: )".
I know it is looking for a ) but I have literally tried putting in every position but still get the error. Thank you for your consideration in helping solve this problem. Below is the entire subroutine.
Sub LastSaturdayIntExtMissTime()
'gets the past Saturday's date based on today.
Dim iWeekday As Integer, LastSaturdayDate As Date, sfx As String
iWeekday = Weekday(Now(), vbSaturday)
LastSaturdayDate = Format(Now - (iWeekday - 1), "mm/dd/yyyy")
Select Case Right(Day(LastSaturdayDate), 1)
Case "1"
sfx = """st"""
Case "2"
sfx = """nd"""
Case "3"
sfx = """rd"""
Case Else
sfx = """th"""
End Select
ActiveWorkbook.Sheets(2).Name = (UCase(Format(Date, "mmm")) & " Data through " & Format(LastSaturdayDate, "mmm d" & sfx) 'this throws a compile error
MsgBox Format(LastSaturdayDate, "mmm d" & sfx) 'this works
End Sub
The line that is erroring out:
ActiveWorkbook.Sheets(2).Name = (UCase(Format(Date, "mmm")) & " Data through " & Format(LastSaturdayDate, "mmm d" & sfx)
Has and extra "(" in front of the equal sign. It should read:
ActiveWorkbook.Sheets(2).Name = UCase(Format(Date, "mmm")) & " Data through " & Format(LastSaturdayDate, "mmm d" & sfx)

I am trying to write a program in VBA that when a document is open a message box will appear that asks for user input to continue.?

In this box it will say what document was opened, the last version that you read of it, and the current up to date version of the document. The documents are named differently and are separated by 3 factors: an example of this would be QRS-RTY-006.G.docm, where QRS-RTY- is the same for all the documents, 006.G is the portion where you tell what version is available that I need to use to identify the current and last read version, and the .docm stays the same for each document.
Current Code:
Dim A As String
Dim B As String = Name
Dim C As String
Dim D As String = Name
A = Split(B, "_")(0)
C = Split(D, "_")(1)
MsgBox("You have opened " & A & " Revision " & C & " . The last revision you read was ___. The current revision is ___. Would you like to compare? ", vbYesNo)
If vbYes Then
End If
This should be a good start :
Private Sub Document_Open()
Dim dName As String, _
dVersion As String, _
mAnswer As Integer, _
SrcFile As String, _
PossFiles As String
dName = Left(ActiveDocument.Name, 7)
dVersion = Right(Left(ActiveDocument.Name, Len(ActiveDocument.Name) - 5), 5)
mAnswer = MsgBox("You have opened : " & dName & ", Revision : " & dVersion & "." & Chr(13) & _
"The last revision you read was ___." & Chr(13) & _
"The current revision is " & dVersion & Chr(13) & _
Chr(13) & Chr(13) & "Would you like to compare? ", vbYesNo)
If mAnswer <> vbYes Then
'vbNo : They don't want to compare
Else
'vbYes : They want to compare
scrFile = Dir(ActiveDocument.Path & "\" & dName & "*.docm")
Do While scrFile <> ""
PossFiles = PossFiles & Dir & Chr(13)
scrFile = Dir
Loop
If PossFiles <> vbNullString Then
MsgBox PossFiles
Else
MsgBox "No other files found"
End If
End If
End Sub