-
OssieMac 416 Reputation points
2021-07-24T06:50:35.86+00:00 I am assuming that by VBA form you mean a Userform.
TextBoxes on Userforms are just that. They accept entries as Text. Therefore when getting the text, it needs to be converted to a date in the required format and then written to the worksheet.
Vice versa. In getting a date from the worksheet and writing to a Userform text box then convert the date to text.
The following example gets the entered date in a text box and converts it to a date value as a serial number.
The split function separates the text date into day, month and year and saves the values in a zero based array (with 3 elements) as follows.
arrSplit(0) is the Day
arrSplit(1) is the Month
arrSplit(2) is the YearDateSerial function converts the separate values to a serial date and assigns the value to a date variable.
The date variable can then be written to the worksheet with the destination number format set as required.
Write the date from the TextBox to the worksheet
Private Sub cmdCopyDate_Click()
Dim arrSplit As Variant
Dim dte As Date
Dim ws As Worksheet
Dim rngDate As RangeSet ws = Worksheets("Sheet1") arrSplit = Split(Me.txtDate, "/") dte = DateSerial(arrSplit(2), arrSplit(1), arrSplit(0)) With ws Set rngDate = .Cells(2, "A") 'Alternatively .Range("A2") End With rngDate.NumberFormat = "dd/mm/yyyy" rngDate.Value = dte
End Sub
Get the Date from the worksheet and write it to a TextBox on the Userform
Private Sub cmdGetDate_Click()
Dim ws As Worksheet Dim rngDate As Range Set ws = Worksheets("Sheet1") With ws Set rngDate = .Cells(2, "A") 'Alternatively .Range("A2") End With Me.txtDate = Format(rngDate.Value, "dd/mm/yyyy")
End Sub
My apologies for the late reply but I did not get an email notification of your comment. I wonder with this forum if emails are sent if a comment is appended or only when "Reply" is clicked and then write the reply.
The first example copies the date from the Userform to a worksheet cell where Me.txtDate is the TextBox control on the Userform and .cells(2,"A") or .Range("A2") is the cell on the worksheet.
The second example does the opposite. It copies a date from the worksheet to a Userform. I included this example because often it is necessary to get a date from the Worksheet and display that date on the Userform.