Store MonthName() function in a string variable - vba

First question here so go easy on me!
I am new to Visual Basic (but not programming) and I am having trouble on a project I am working on for a local organization.
I have a button that runs a query that contains a single "SELECT ... INTO ... " statement. This statement also looks for every record where the field RecievedBoxToday is equal to "Yes". Here is the code that is working just fine:
SELECT * INTO RENAME_THIS_TABLE
FROM [DATABASE ZERO]
WHERE (([DATABASE ZERO].RecievedBoxToday)=Yes);
Now here is the problem (besides the fact that Received is spelled wrong): This code will be ran every month, but the table (RENAME_THIS_TABLE) is over-written every time the button is clicked. I would like to have permanent data for every month so my solution is to rename the RENAME_THIS_TABLE table to MONTHNAME_YEAR where MONTHNAME is the name of the month (January or December) and YEAR is the current year (2015). I thought I could go about doing this with the MonthName() function, which works just fine, but I want to be able to store this month name into a string to be concatenated with the year (also a string). Afterwords this string will replace RENAME_THIS_TABLE.
My code for this that doesn't seem to work is:
dim Month As String
dim Year As String
MonthName(Month(Date()), False) As Month
Year(Date()) As Year
dim NewName As String = Month + "_" + Year
After this I'm not sure where to go as far as taking this new string variable and inserting into the SQL code, where it will replace RENAME_THIS TABLE.
How can I make this work? Can I make this work? If it matters, I am using VBA with Microsoft Access 2013. Any help is greatly appreciated!

Don't use Month and Year as variable names. Those are reserved (function) names in VBA. Also, as a shortcut, you can just use the Format() function to format your date string:
Dim strNewName As String
strNewName = Format(Date, "mmmm_yyyy") ' => "August_2015"
If your SQL statement is stored in a separate string, you can just concatenate your new table name into your string:
Dim strSql As String
strSql = "SELECT * INTO " & strNewName & " FROM [DATABASE ZERO] WHERE (([DATABASE ZERO].RecievedBoxToday)=Yes);"

Related

String to date error (Conversion from string to type date is not valid)

I want to crate date as MS Access like date (example -> #mm/dd/yyy#) input date can be string or date so I have created object variable to hold value of date. Then I convert it to msaccess date.
but it gives error. See the picture attached.
Before posting this question I had searched a lot, but I don't understand the solutions I found.
A major solution is ParseExact("Date String", "Format", System. IFormatProvider). But in my editor Intellisense does not recognize culturevalue. It tells me culturevalue is not defined.
Then I tried Date.tryparse(). It worked, but if I have to use this, then what is use of CDate conversion function?
Edit 1 :
Date.tryparse() does not work it returns false
in vb6
"#" & Month(dateIn) & "/" & Day(dateIn) & "/" & Year(dateIn) & "#"
works perfectly
It seems that you ask for a string expression for a VBA date value.
That can be done like this:
Dim DateIn As DateTime
DateIn = DateTime.Today
Dim Rval As String
Rval = DateIn.ToString("'#'MM'/'dd'/'yyyy'#'")
Console.WriteLine(Rval)
' Output:
' #07/10/2022#

SQL: Compare Date Range in a String text field

I have an MS Access db. I am writing an application in C# to access it. I have a field "FileName" of type "Short Text in MS Access. Data in FileName field is like "Test 11-12-2004 15.11.15".
Using a Date Range, I got to search records based on FileName field. I am not able to get - How do I compare the date of this format and retrieve the records ? FileName is a Text type and date is a substring of it. Retrieving only the date part and comparing with >= beginDate && <= endDate seems like a puzzle to me.
Can anyone suggest how do I write SQL query to perform this date range comparision and retrieve those records - "Select * from TestHead where FileName......" ????
Any help is appreciated.
Thanks a lot,
In your C# code, as you are going through the records, I'd split the string like this:
char[] delimiters = {' '};
string[] FileNameParts = FileName.Split(delimiters);
This will result in an array FileNameParts, the second element of which will contain the date, which you can convert to an actual date for use in the query:
DateTime FileNameDate = Convert.ToDateTime(FileNameParts(1))
Something along the lines of:
sSQL = "SELECT * FROM Table WHERE " & beginDate & " <= " & FileNameDate
I see this as preferable to adding a column to your table that contains the date substring of the FileName field, because then you constantly need to be updating that column whenever existing records are modified or new records are added. That means more clutter on the C# side, or an UPDATE query on the Access side which at least needs to get called periodically. Either way it would be more communication with the database.

Searching data by date - error

I'm using my VB.Net program to query a database in MS Access. In the database, I have a table that contain a "question_start" (Date/Time) field.
I would like to return the IDs of each record that occur on or after a date that I choose in my VB programme.
The data in the Access table, is being stored as Date/Time under a General Date format (e.g. '10/10/2016 15:48:01').
In VB.NEt, I am using the DateTimePicker object to select the date.
Below is the code I'm using to bring back all records that have a Start Date of 10/10/2016 (10th October 2016).
(Note 1: I have removed the time element from this particular search as I do not need my results to be time-sensitive here but are required later.)
Private Sub btnDateText_Click(sender As Object, e As EventArgs) Handles btnDateText.Click
Dim dt_QuestionDate As New DataTable()
dt_QuestionDate = getData("SELECT question_id
FROM tblQuestion
WHERE question_start => " & dtDateText.Value.ToString("dd-MM-yyyy") & ""
)
lstDateText.DataSource = dt_QuestionDate
lstDateText.DisplayMember = "question_id"
lstDateText.ValueMember = "question_id"
End Sub
**There are records in my database that should be returned, but I am receiving no values currently. I am not sure if it is how I've written the WHERE clause (I've done WHERE with "=>", ">=", and also "=") but I am not receiving records with the 10/10/2016.
Has anyone any ideas please? I don't know if it's because it's a simple mistake, or because of the time element that is stored in Access?
You need proper formatting of the string expression for the date value:
WHERE question_start => #" & dtDateText.Value.ToString("yyyy'/'MM'/'dd") & "#"

Date Subtraction within Select Statement

I am currently working on an MS Access database, and am having problem with date subtraction.
Essentially I am trying to create a target date for example:
Target Date = Deadline - Lead Time
i.e. the lead time could be 30 days, therefore the target date should be 30 days prior to the deadline.
The code I am trying to use is this:
strSQL = "INSERT INTO dbo_DEALER_TASK ( Dlr_Number, Action_Id, Task_Id, Area_Id,
Task_Deadline_Date, Responsible_Person_Id, Alternate_Person_Id, Priority, Comment,
Suppress_Email, Dealer_Type ) "
strSQL = strSQL & "SELECT dbo_DEALER_ACTION.Dlr_Number, dbo_DEALER_ACTION.Action_Id,
qryAllTasksToAdd.Task_Id, qryAllTasksToAdd.Area_Id, Deadline_Date - Deadline_adjustment
AS 'Task_Deadline_Date', qryAllTasksToAdd.Person_Responsible_Id,
qryAllTasksToAdd.Alternate_Responsible_Id, qryAllTasksToAdd.Priority,
qryAllTasksToAdd.Comment, qryAllTasksToAdd.Suppress_Email,
qryAllTasksToAdd.Applies_To_Dealer_Type "
strSQL = strSQL & "FROM dbo_DEALER_ACTION LEFT JOIN qryAllTasksToAdd ON
(dbo_DEALER_ACTION.Dealer_Type = qryAllTasksToAdd.Applies_To_Dealer_Type) AND
(dbo_DEALER_ACTION.Action_Id = qryAllTasksToAdd.Action_Id) "
strSQL = strSQL & WHERE (((qryAllTasksToAdd.Task_Id)=" & Me.Task_Id & ") AND
((dbo_DEALER_ACTION.Date_Completed) Is Null));"
DoCmd.RunSQL strSQL
When the VBA code executes the statement, everything is updated correctly, except for the Task_Deadline_Date field, which is being left blank.
What is really confusing me though is if I run this SQL statement standalone it is working as expected. After trying a number of different ideas I tried to replace "Deadline_Date - Deadline_adjustment AS 'Task_Deadline_Date'" with a string literal date and the statement then worked fine
Does anybody have any ideas what is going wrong?
Thanks,
Chris
You have quoted the alias, you should not do that:
Deadline_Date - Deadline_adjustment AS Task_Deadline_Date
Not
Deadline_Date - Deadline_adjustment AS 'Task_Deadline_Date'
When you add the quotes, the name of the field is 'Task_Deadline_Date'
Depending on the data type of your date field and whether or not you are using SQL Server, you may need to use DateAdd, for example:
DateAdd("d",-[Deadline_adjustment],[Deadline_Date])
In Access' query designer, start with the version of your query which works and convert it to a parameter query.
WHERE
qryAllTasksToAdd.Task_Id=[which_id]
AND dbo_DEALER_ACTION.Date_Completed Is Null;
You can also add a PARAMETERS statement at the start of the query to inform the db engine about the data type of your parameter. Examples ...
PARAMETERS which_id Text ( 255 );
PARAMETERS which_id Long;
Once you get that query working, save it and give it a name. Then your VBA procedure can use that saved query, feed it the parameter value, and execute it.
Dim db As DAO.database
Dim qdf As DAO.QueryDef
Set db = CurrentDb
Set qdf = db.QueryDefs("YourQuery")
qdf.Parameters("which_id").value = Me.Task_Id
qdf.Execute dbFailOnError
Set qdf = Nothing
Set db = Nothing
This should be much easier than trying to recreate that SQL statement in VBA code each time you need to execute it.
It sounds like the data type of the column you are inserting in dbo_DEALER_TASK is not actually a datetime field.
I tried to replace "Deadline_Date - Deadline_adjustment AS 'Task_Deadline_Date'" with a string literal date and the statement then worked fine
If you mean '02/20/2012' (as you would correctly use on SQL Server, for example) then this shouldn't work in Access and only will if your output column is a text (= varchar/char)) data type. Date constants in Access are specified like #02/20/2012#
Please confirm the data type of Task_Deadline_Date in your output table.

Dealing with dates in dd/mm/yyyy format

I have a VB6 application which works with datetime values in SQL Server (which are obviously storing dates as mm/dd/yyyy).
I need to represent these dates to the user as dd/mm/yyyy, read them in as dd/mm/yyyy, and then store them back into the database as the standard mm/dd/yyyy.
This is the current code snippets I have which pull + insert the dates, however I have read many conflicting methods of handling the conversions, and I was wondering if anyone here knew a clear solution for this situation.
"SELECT * FROM List WHERE DateIn LIKE '%" & txtDateIn.Text & "%'"
"UPDATE [Progress] SET [Date] = '" & txtDate.Text & "'"
txtDate.Text = "" & RecordSet.Fields("Date").Value
Any thoughts? Thanks in advance.
**Update
Actually I just noticed I do have dates stored in datetime fields in the form of 16/08/2009 00:00:00 which is dd/mm/yyyy. So perhaps I misunderstood the problem. But when trying to update the datetime value I have been getting 'The conversion of char data type to a datetime data type resulted in an out-of-range datetime value.'.
I assumed this was because the date formats did not match (causing a problem with having a month value out of range) however I do have date values in the format of day/month/year in the datetime field already. And the date being submitted to the database is definitely dd/mm/yyyy.
**** Update 2**
Ok, there seems to be some confusion I have caused. I apologize.
I am storing the dates as datetime in the SQL database
The texts are TextBox controls in the VB6 application
I am running SQL SELECT statements to read the dates from the database and place the value in a TextBox
I then have a 'commit' command button which then performs an UPDATE SQL statement to place the value of the TextBox into the datetime field in the SQL database
This works perfectly fine until 1 specific occasion.
In this occasion I have a datetime value (which SQL Server 2005 displays as 16/08/2009 00:00:00) which is read from the database and populated the TextBox with the value 16/08/2009. Now when I try to run the UPDATE statement without modifying the TextBox text I get the error 'The conversion of char data type to a datetime data type resulted in an out-of-range datetime value.'
This does not occur with other records such as one where the date is 04/08/2009 so the only issue I can see is possibly with the position of day and month in the value because if the DB is expecting month first then obviously 16/08/2009 would be out-of-range. However the value in the database is already 16/08/2009 with no issues.
SQL Server doesn't "obviously" store dates as mm/dd/yyyy. It doesn't store them in a text format at all, as far as I'm aware.
I don't know what the VB6 support for parameterised queries is, but that's what you want: basically you want to pass the argument to the query as a date rather than as text. Basically you should parse the user input into a date (in whatever way VB6 does this) and then pass it through in the paramterised query.
EDIT: I've tried to find out how VB6 handles parameterised queries, and not had a great deal of luck - hopefully any good book on VB6 will cover it. (There are loads of examples for VB.NET, of course...) There's a Wrox post which gives an example; that may be enough to get you going.
EDIT: As the comment to this answer and the edit to this question edit indicate, there's some confusion as to what your data types really are. Please don't use character-based fields to store dates: no good can come of that. Use a proper date/datetime/whatever field, and then make sure you use parameterised queries to access the database so that the driver can do any necessary conversions. Relying on a text format at all is a bad idea.
Use the ODBC Canonical form of the date or timestamp in your queries.
This avoids any misunderstanding due to localization when storing the dates.
The timestamp format is {ts 'yyyy-mm-dd hh:mm:ss[.fff]'}
The date format is {d 'yyyy-mm-dd'}
Here are the functions I use for this.
Now as for entry and display in VB6. Ideally you'd be using the datetimepicker control instead of a textbox as that returns a date and there is no misunderstanding when using it which date you are picking. But if you can assume it is always DD/MM/YYYY (that is a big if), you can use Format(datevalue, "DD/MM/YYYY") to display it. To read it into a date variable you can't just use CDate. You'll need to use parsing and something like DateSerial to put it together: DateSerial(Right(strDate, 4), Mid(strDate, 4, 2), Mid(strDate, 1, 2)).
' ------------------------------------------------------------------------------
' DateLiteral
'
' Description :
' given a vb date, it returns a string with the odbc canonical date format.
'
' History
' 2008-02-04 - WSR : added to this project
'
Public Function DateLiteral(ByRef dtSource As Date) As String
DateLiteral = _
"{d '" & LeftPadDigits(Year(dtSource), 4) & "-" & _
LeftPadDigits(Month(dtSource), 2) & "-" & _
LeftPadDigits(Day(dtSource), 2) & "'}"
End Function
' ------------------------------------------------------------------------------
' ------------------------------------------------------------------------------
' TimeStampLiteral
'
' Description :
' given a vb date, it returns a string with the odbc canonical timestamp format.
'
' History
' 2008-02-04 - WSR : added to this project
'
Public Function TimeStampLiteral(ByRef dtSource As Date) As String
TimeStampLiteral = _
"{ts '" & LeftPadDigits(Year(dtSource), 4) & "-" & _
LeftPadDigits(Month(dtSource), 2) & "-" & _
LeftPadDigits(Day(dtSource), 2) & " " & _
LeftPadDigits(Hour(dtSource), 2) & ":" & _
LeftPadDigits(Minute(dtSource), 2) & ":" & _
LeftPadDigits(Second(dtSource), 2) & "'}"
End Function
' ------------------------------------------------------------------------------
' ------------------------------------------------------------------------------
' LeftPadDigits
'
' Description : pads the given string to the left with zeroes if it is under
' the given length so that it is at least as long as the given length.
'
' History
' 2008-02-04 - WSR : added to this project
'
Public Function LeftPadDigits(ByVal strSource As String, ByVal lngLength As Long) As String
If Len(strSource) < lngLength Then
LeftPadDigits = String$(lngLength - Len(strSource), "0") & strSource
Else
LeftPadDigits = strSource
End If
End Function
' ------------------------------------------------------------------------------
Also should be noted, yes the first choice is to use ADO and parameterized queries.
In my case I access the database through a third party library and can't use parameterized queries. Thus the date literal handling. Here is an example of the ADO parameterized queries though. The code can be different depending on which type of ADO connection you are using though: OLEDB, ODBC or SQLNative. Sometimes it isn't just a ? for the parameter marker. This example is OLEDB.
Set cmdVerifyUser = New ADODB.Command
cmdVerifyUser.CommandType = adCmdText
cmdVerifyUser.CommandTimeout = 30
cmdVerifyUser.CommandText = "SELECT username FROM users WHERE userid = ?"
cmdVerifyUser.Parameters.Append cmdVerifyUser.CreateParameter("userid", adVarChar, adParamInput, Len(m_strUserName), m_strUserName)
cmdVerifyUser.ActiveConnection = m_conDatabase
Set rstResults = cmdVerifyUser.Execute()
If Not rstResults.EOF Then
Well after all of that the problem was simple. I have the date value wrapped in single (') and double (") quotes. The problem was encountered due to date values not requiring the single quotes. Removing them solved the issue.
Thank you anyway for trying to help all.