Can an unbound text box containing a string be set to equal a date(time) field programatically? - vba

Alright. The goal is to programatically grab a string of numbers from an unbound control on a form. Why? I have a form that contains two controls for a start time and a finish time. The format for these controls are dd/mm/yyyy hh:dd. The end users are complaining that they hate having to take the time to enter the date and time in a single field, especially considering the old form (a horrible Excel spreadsheet where users could type whatever they felt like typing), allowed them to just type the 4-digit time. I am trying to replicate that experience, but as we know, date and time are wrapped into one field in Access.
The idea is to supply the date/time field with the values from the string using separate unbound control. For example, one control will be labelled 'Start Time' and will accept 4 numbers with an input mask of 99:99. Before the form is updated, I would like to pass the string from the control Unfortunately, I do not have the code, but I will attempt to build psuedo code here:
Class Level Module
Private Sub Form_BeforeUpdate(Cancel As Integer)
strStartTime as String
strFinishTime as String
strDate as String
rstDailyLog as recordset
Set rstDailylog = CurrentDb.OpenRecordset ("Daily Log" dbOpenDynaset)
'assign variables to unbound controls on form
strStartTime = Me![Start Time]
strFinishTime = Me![Finish Time]
'Here, I assume I begin parsing my string to the date/time field
'function to edit send the string to the actual date/time field
'Basically, copied from Microsoft Docs
Sub EditName(rstCovertString As Recordset, strStart As String, strFinish As String)
With rstConvertString
.Edit
![Start Time] = strStart
![Finish Time] = strFinish
.Update
.Bookmark = .LastModified
End With
What are the implications of doing so? For example, if the bound form displays a record with an unbound value, how will that record display the desired data?
As I was building this code, I just realized that the field that holds the date/time is a date/time data type?
Now I am really confused. If they are different data types, can I even send my start/finish variables to that control as a string?

It turns out that Access does a TRUCKLOAD of data type conversions for you.
When text box controls are bound to a underlying table, then that text box will return a datetime data type. Even if you stuff in a string - it gets converted to a datetime data type behind the scenes.
And same goes for text, or if the control is bound to a number. (again, data type forcing is actually occurring here. However, VBA is rather forgiving in this regards.
Thus, most of the time you don't notice this issue.
HOWEVER, WHEN the text box is NOT bound to a underlying table, then the data type of that text box is more loosely goosey.
So, set the format of the un-bound text box to date format. If you do this, then even assigning a string value to the text box will cause access to convert the string into a date time. In fact, your code should STILL take the data from that table, and if you are not directly assigining the date column to the text box?
Well, then format the string as USA format.
eg:
me.MyStartDate = format(dtValue, "MM/DD/YYYY")
or
me.MyStartDate = format(dtValue, "YYYY-MM-DD")
You will find that EVEN if your date format is different then above (say based on your computers regional settings), then Access will convert the above to an interal date format, and THEN display what your regional settings are REGARDLESS of the above.
So, your display might be:
DD/MM/YYYY (day first)
But, doing this:
me.MyStartDate = dtvalue
or
me.MyStartDate = format(dtValue,"YYYY-MM-DD")
will work.
So, do NOT convert the datetime value from the table into a string IF POSSIBLE to avoid doing so.
So, you simply assign that actual datetime value directly it to the text box. As long as Access sees and knows that text box has a date format, then it will assume and work with that text box as a date time data type.
The above ONLY works if you set the un-bound text box to have some kind of date formatting. Once you told access that the text box is a date type text box, then directly assign date values from a table (without conversion to a string) is your BEST solution.
As noted, for bound text boxes then the text box will take on the correct datatype - even if you don't format the text box.
And the same above trick also applies to number formats. And thus setting a number format for the text box will result in that text box NOT being a string/text type, but an actual number.
So, you can force/set un-bound text boxes to a given data type by use of the formatting option. Once you do this, then you should not need to format data from a table, but in fact just shove the actual date value into the text box. You can (and should) thus now be able to set any kind of date formatting you want for the text box - even setting that is the exact opposite of the actual date format your computer (and user) has chosen on a whim.
In other words, if you do this correct?
Then you don't care, or even have to know the date format settings on any given computer, and your code will always work.
Of all the suggestions here by me?
If possible, assign the actual date value to the text box, and do NOT format the string. This will allow you to set any kind of date/time format for the text box.
Once you defined/set the text box to be a date format, then it is a datetime thing and data type. As a result, you should not require any conversion from the table data to set/fill out the text box.
Edit
You have:
'assign variables to unbound controls on form
strStartTime = Me![Start Time]
strFinishTime = Me![Finish Time]
No! - declare the above two vars as date, not strings.
dim dtStartTime as date
dim dtFinishTime as date
now:
dtStartTime = Me![Start Time]
dtFinishTime = Me![Finish Time]
'Here, I assume I begin parsing my string to the date/time field
No, don't parse. You have the data as a internal datetime. How you display this data is up to you or the users regional settings. As a developer, it is a date type and a date "thing". Don't convert to string!!!
'function to edit send the string to the actual date/time field
'Basically, copied from Microsoft Docs
Sub EditName(rstCovertString As Dao.Recordset, dtStart As Date, _
dtFinish As date)

Access will often recognize a string with a date/time structure as a date/time value. Could use CDate() function to be sure or use # delimiters.
Do these tests in VBA editor immediate window.
?IsDate("1/1/2020 14:50")
?IsDate(CDate("1/1/2020 14:50"))
?IsDate(#1/1/2020 14:50#)
?IsDate("1/1/2020" & " " & "14:50")
All return True.
If you want to display the saved date/time then bind a textbox to the field. Lock the control if you don't want users to edit in it. Then use VBA to save any edits done in the unbound textboxes. I recommend AfterUpdate event for code to save. Use BeforeUpate event to validate user input.

Related

Trim function causes date format change

Firstly, important to note that I'm in the UK so standard date format is dd/mm/yyyy
In a A1, I have a date: 02/05/2017 (dd/mm/yyyy)
I can confirm this in the immediate window:
?CLng(Range("A1").Value)
42857
Now, if I do the following:
Range("A1").Value = Range("A1").Value
you can probably guess, nothing happens - the date is still 02/05/2017 and the numeric value is still 42857
But if I use trim with it:
Range("A1").Value = Trim(Range("A1").Value)
The date is changed to 05/02/2017. This isn't just formatting - the numeric value has also changed to 42771.
What is it about the Trim() method that causes the date to be read in US format and then converted back to UK format with a new date value? Is this a bug?
From the discussion in comments:
The default or "token" format in VBA (not Excel itself, as Macro Man rightly pointed out) is US English - regardless of regional settings or cell formatting.
When you do VBA text functions on a date, the output of those functions are in text format. So the result of Trim(Range("A1").Value) is a string. This string happens to resemble a proper US date, so when you insert it into a cell, Excel recognizes it as a US date.
So two implicit conversions happen. The first happens when you read the cell contents and pass it to trim(): date->text conversion; the second happens when you write it back to an Excel cell: text->date conversion. The second conversion has no information about the format, so it assumes US English.
(You should be able to achieve the same result with any text function, not just trim().)
I found out that if you add "'" before the date, the date is not altered.
Range("A1").Value = "'"&Trim(Range("A1").Value)

Excel VBA InputBox value is not a date

I have a user input box where you type in a string, annoyingly this string looks like a date 00/00/0000 and excel reformats it as such.
When the value can't be a date ex. 18/19/4561 (month can't be 18 or 19) it displays it correctly.
But whenever it can be seen as a possible date it switches things around.
I've tried setting the value as a string rather than nothing but excel still changes it when putting it in the page.
When I try manually inputting it in the cell or equal the values from a manually entered cell it works fine.
But whenever I get it from the inputbox it messes with it. Even when I hard code the string to a variable (x = "05/06/4564") it switches things around.
How do I force excel to leave the string as is?
Prefix the value with a single apostrophe and Excel will interpret it as a string.
Eg '18/19/4561
Also, have you tried setting the cell format to Text

How to use UserForm Values for multiple things

I have UserForm1 which is a multipage userform and I am trying to access the information that was gathered through the form in a sub located in Module1. This sub will need to access several different values and do different things with those values so this is going to be a multipart question.
I have the below code in which I attempt to use one of the values as the upper limit of a For Next Loop. However the current problem is that when the code reaches this line it jumps to the Userform_Initialize routine.
For X = 1 To UserForm1.LocalOffer.Value
Second part of this question comes from inside the For Next loop from above. Where I have the below code. Which would ideally allow me to cycle through a series of similarly named Textboxes from the userform. Not even sure if that will work as the code keeps breaking before getting to that part.
Range("B" & X).Value = UserForm1.Controls("LocalTier" & Tier).Value
Last Part of this question if I have a Textbox in the userform that contains a date in the format 1/18/2015 is there a way for me to grab just a portion of that date say for instance just the Day or just the last digit of the year?
I am using Excel 2013 but the file will be ran on Excel 2007
Edit:
Turns out that problem 1 was fixed by not closing the userform with the X button but instead adding a line to hide the userform when you hit the last button. As it turns out my code for the second question worked just fine once i got past that. Only question left is the last one which I have no ideas on.
As from the comments, I see you don't need anymore to know about points 1 and 2, I will hence limit my answer to the point 3.
Last Part of this question if I have a Textbox in the userform that contains a date in the format 1/18/2015 is there a way for me to grab just a portion of that date say for instance just the Day or just the last digit of the year?
You can use either string manipulation, or date conversion.
Let's assume the Textbox is called myDateTextbox
String manipulation
Among the string manipulators that VBA provides, I would cite Left() and Right().
For example:
last_digit_of_the_year = Right(myDateTextbox.Text, 1)
will return you the last character of the string. On the other hand:
first_digit = Left(myDateTextBox.Text,1)
will return you the first digit of the string.
You can use the Len(myDateTextBox.Text) built-in to return the current length of the string.
Date conversion
You can simply convert your string into date using the CDate() function. Please note this function will return an error if you pass an invalid string. If your textbox contains 24/01/1990, you can first convert the string into a date:
myDate = CDate(myDateTextBox.Text)
Hence, you can retrieve day, month or year like this:
myYear = Year(myDate)
myMonth = Month(myDate)
myDay = Day(myDate)
Please note that CDate recognizes date formats according to the locale setting of your system.. Hence, if the format in the TextBox is not the same than the one of your system, then consider manipulating the string before to adapt it to the proper format. For example, if your system has settings DD/MM/YYYY and your textbox shows a MM/DD/YYYY type, you can "adjust it" as follows:
wrongFormat = myDateTextBox.Text
splittedDate = Split(wrongFormat,"/")
goodFormat = splittedDate(1) & "/" & splittedDate(0) & "/" splittedDate(2)
If wrongFormat was 1/18/2014 but your system would like to read it as 18/1/2014, it's now fine because goodFormat will be equal to 18/1/2014 after the split and re-build.

VBA Userforms. Textbox as number value to cell

I've been searching for a solution to this for a while and have been unsuccessful in finding. Essentially, I have the user of my document populating fields in a user form that my code then puts into the appropriate cells. One of these input fields is a number but, no matter how I instruct excel to format the cell, it still is text in the end and I can't perform any calculations. I'm sure this is probably a pretty simple fix but I've been unsuccessful so far in finding a solution. As always, any help is appreciated!
thanks!
You need to convert the value from text to a numeric type before putting it into a cell.
Assuming your textbox is called txtNumber and you're outputting to cell Output!A1, the code would be:
Sheets("Output").Range("A1") = CDbl(txtNumber)
Other conversion functions you might want to use are CLng (convert to Long), CInt (convert to Integer), CDec (convert to decimal, useful for currency values).
This code will raise an error if the user types a non-numeric text value into the field. You should validate on the textbox's Change event and disable the OK button if invalid data is inputted.

Date format issue in SSRS

I have an issue with date format in my SSRS. I am saving date from DateTimePicker to database. From there I am taking display in my datagridview using following
dgv.items(0,2).value=Format(Cdate(dsSaver.tblInv.rows(0).items(0)),"dd-MMM-yyyy")
This displays it correctly (04-Nov-2011) but when I take date from the same database to my SSRS using
="Dated: " &Format(cdate(Fields!InvDate.Value),"dd-MMM-yyyy")
It displays it like 11-Apr-2011.
I have tested all winforms fare displaying it right but all SSRS are displaying it wrong.
Please advise.
A couple of things are going on here. The date is being saved appropriately but is being displayed incorrectly due to your formatting options. This line is quite problematic:
="Dated: " & Format(cdate(Fields!InvDate.Value), "dd-MMM-yyyy")
CDate takes a value, generally a string, and converts it to a date, which you are then taking and formatting back into a string. Now, by default reports are set to have their Language property set to English (United States) so the CDate function is taking the string representation of the date 04-Nov-2011 to be 04/11/2011 which it is then converting, using the US format of MM-dd-yyyy (not the Pakistani one) into being the date 11-Apr-2011 because it thinks the month comes first.
So, you should change your Language setting of your report to =User!Language so that it supports whatever the user's language is and will format things appropriately. This may be enough to make your expression work.
Regardless, if Fields!InvDate.Value is being supplied as a date field (as it should be) there is no need for the CDate function and this should work:
="Dated: " & Format(Fields!InvDate.Value, "dd-MMM-yyyy")
There is also the FormatDateTime function but unfortunately it doesn't support the format you want to use.
Have you looked at the RDLC options for Formatting a Report: Format the Date?