entering date in a cell - excel

I have a button, which when clicked will give the current date and time in a text box.then I used another program to move that to cell.but this are not considered as the date until I double-clicked it.during filtering,this entered date are excluded from other dates
i have done formatting for date(ddmmyy HHmm)
Private Sub CommandButton5_Click()
If Not TextBox6.Value = "" Then
ans = msgbox(" Date already exits.Do you want to continue", vbYesNo + vbQuestion)
If ans = vbYes Then
TextBox6.Value = Format(Now(), ddmmyyHHmm)
End If
End If
If TextBox6.Value = "" Then
TextBox6.Value = Format(Now(), ddmmyyHHmm)
End If
End Sub
and for copying value to cell ,i used
cells(i,"A").value = textbox6.value

Format returns a Variant/String. You want to enter an actual date/time into the cell, not a formatted one that Excel no longer recognizes as a date.
One option is to use DateSerial and TimeSerial to build up a true date/time from that string. There's probably a simpler way to achieve this though, but anyway, here's an example:
Dim x As String
x = TextBox6.Value
Dim yy As Integer, dd As Integer, mm As Integer, hh As Integer, min As Integer
yy = CInt(Mid(x, 5, 2)) ' year
mm = CInt(Mid(x, 3, 2)) ' month
dd = CInt(Mid(x, 1, 2)) ' day
hh = CInt(Mid(x, 7, 2)) ' hour
min = CInt(Mid(x, 9, 2)) ' minute
Cells(i, "A").Value = DateSerial(yy, mm, dd) + TimeSerial(hh, min, 0)
If you want to format the cell with that date/time formatting:
Cells(i, "A").NumberFormat = "ddmmyyHHmm"

Related

Compare dates using VBA

I am trying to parse sheet with time stamps and count number of occurrences.
my data have header (date, hour, instance, day), so I want to parse through days and when there is new day I record time (this is time of first event that day) and increment counter next to that "time" value (I add list of timestamps at column 11)
My code is:
Sub Count()
Dim i As Integer
Dim j As Integer
Dim Day As String
Dim Vrijeme As Date
Dim test As Date
For i = 1 To 5673
If Cells(i, 4).Value <> Day Then
Day = Cells(i, 4).Value
Vrijeme = Cells(i + 1, 2).Value
For j = 5 To 500
test = Cells(j, 11).Value
If Vrijeme = test Then // This is place that doesn t work
counter = Cells(j, 12).Value
counter = counter + 1
Cells(j, 12).Value = counter
End If
DoEvents
Next j
End If
Next i
End Sub
But this doesn t work, I event manualy set cell format to "Time" ... any idea why this doesn t work. when I do debug variable read data correctly but when it compare values this don t work ...
thx
try to use TimebValue and DateValue.
as
Day = DateValue(Cells(i, 4))
Vrijeme = TimeValue(Cells(i + 1, 2))
test = TimebValue (Cells(j, 11))
You need to compare comparable values, to be 100% sure that they are comparable convert them bout in one format.

Excel VBA convert Date with time

I have 2 cells with time data that format as follows:
"A1" = Sep 01 2018 00:01:33.707
"A2" = Sep 01 2018 00:01:49.917
I need to create a button and method within excel VBA that will set "A3" cell to true if the time "A2" is more than "A1" by 90 seconds.
This is what i have so far but it does not work:
Sub Macro2()
Dim str1 As String, str2 As String
With Worksheets("sheet5")
str1 = .Cells(1, "A").Text
str2 = .Cells(2, "A").Text
'greater than 90m seconds in A3
.Cells(3, "A") = CBool(Abs((DateValue(Left(str1, 6) & "," & Mid(str1, 7, 5)) + _
TimeValue(Mid(str1, 13, 8)) + TimeSerial(0, 0, 1) * CDbl(Right(str1, 4))) - _
(DateValue(Left(str2, 6) & "," & Mid(str2, 7, 5)) + _
TimeValue(Mid(str2, 13, 8)) + TimeSerial(0, 0, 1) * CDbl(Right(str2, 4)))) > _
TimeSerial(0, 0, 90))
'actual absolute difference in A4
.Cells(4, "A") = Abs((DateValue(Left(str1, 6) & "," & Mid(str1, 7, 5)) + _
TimeValue(Mid(str1, 13, 8)) + TimeSerial(0, 0, 1) * CDbl(Right(str1, 4))) - _
(DateValue(Left(str2, 6) & "," & Mid(str2, 7, 5)) + _
TimeValue(Mid(str2, 13, 8)) + TimeSerial(0, 0, 1) * CDbl(Right(str2, 4))))
End With End Sub
The above gives error because Date functions works with system Locale, which in my case is Hebrew, while the Data is in English.
Another way that could help is to convert all the column "A" (which holds the dates) to a system local date that can be used with Date and time functions on VBA (don't know how to do that).
Please help
I have split your task into 3 functions.
a) a helper function converts the 3 characters of the month into an integer. It looks a little clumsy, there might be other approaches but the advantage of using a large Select Case is it is easy to understand and easy to adapt if month names in a different language arise:
Function getMonthFromName(monthName As String) As Integer
Select Case UCase(monthName)
Case "JAN": getMonthFromName = 1
Case "FEB": getMonthFromName = 2
Case "MAR": getMonthFromName = 3
Case "APR": getMonthFromName = 4
(...)
Case "SEP": getMonthFromName = 9
(...)
End Select
End Function
b) a function that converts the string into a date. It assumes the date format in the form you provided, but it is easily adapted if the format changes (for simplicity, the seconds are rounded)
Function GetDateFromString(dt As String) As Date
Dim tokens() As String
tokens = Split(Replace(dt, ":", " "), " ")
Dim day As Integer, month As Integer, year As Integer
month = getMonthFromName(CStr(tokens(0)))
day = Val(tokens(1))
year = Val(tokens(2))
Dim hour As Integer, minute As Integer, second As Double
hour = Val(tokens(3))
minute = Val(tokens(4))
second = Round(Val(tokens(5)), 0)
GetDateFromString = DateSerial(year, month, day) + TimeSerial(hour, minute, second)
End Function
c) A function that calculated the difference of the 2 dates in seconds. A date in VBA (and many other environments) is stored as Double, where the Date-Part is the integer part and the date is the remainder. This makes it easy to calculate with Date values.
Function DateDiffInSeconds(d1 As String, d2 As String) As Long
Dim diff As Double
diff = GetDateFromString(d2) - GetDateFromString(d1)
DateDiffInSeconds = diff * 24 * 60 * 60
End Function
Update to deal with milliseconds: Change the GetDateFromString-function. In that case, DateDiffInSeconds should return a double rather than a long.
Function GetDateFromString(dt As String) As Date
Const MillSecPerHour As Long = 24& * 60 * 60 * 1000
Dim tokens() As String
tokens = Split(Replace(Replace(dt, ".", " "), ":", " "), " ")
Dim day As Integer, month As Integer, year As Integer
month = getMonthFromName(CStr(tokens(0)))
day = Val(tokens(1))
year = Val(tokens(2))
Dim hour As Integer, minute As Integer, second As Integer, milli As Integer
hour = Val(tokens(3))
minute = Val(tokens(4))
second = Val(tokens(5))
milli = Val(tokens(6))
GetDateFromString = DateSerial(year, month, day) _
+ TimeSerial(hour, minute, second) _
+ milli / MillSecPerHour
End Function
For your information, I've done what you are doing in a slightly different (and easier) way:
In cell B2, I put the value 13/11/2018 11:44:00.
In cell B3, I put the value 13/11/2018 11:45:01.
(For both cells, the cell formatting has been set to d/mm/jjjj u:mm:ss).
In another cell, I put following formula:
=IF((B3-B2)*86400>90;TRUE;FALSE)
The formula is based on the idea that a datetime value is set, based on the idea that one day equals 1, and there are 86400 seconds in one day.
Like this, you can calculate time differences without needing VBA.
I think you are over-complicating it, try this to get an idea how to do it:
Sub Macro2()
Dim str1 As String, str2 As String
With Worksheets("sheet5")
.Range("b1:e1") = Split(Range("A1"), " ")
.Range("B2:e2") = Split(Range("A2"), " ")
End Sub
Use UDF.
Sub Macro2()
Dim str1 As String, str2 As String
Dim mySecond As Double, t1 As Double, t2 As Double, t3 As Double
mySecond = TimeSerial(0, 0, 90)
With Worksheets("sheet5")
str1 = .Cells(1, "A").Text
str2 = .Cells(2, "A").Text
t1 = ConvertTime(str1)
t2 = ConvertTime(str2)
t3 = t2 - t1
.Cells(3, "a") = Abs(t3) >= mySecond
End With
End Sub
Function ConvertTime(s As String)
Dim vS
vS = Split(s, " ")
ConvertTime = DateValue(vS(0) & "-" & vS(1) & "-" & vS(2)) + TimeValue(Split(vS(3), ".")(0))
End Function

How do I split a custom DateTime format in excel using VB Macros?

I have a document with the following:
FullDateTime FullDate FullTime Day Month Year Hour Minute Second
dd/mm/yyyy hh:mm:ss AM/PM
and I would like to fill in the other columns using macros to split the first column and place the whole date, whole time, day, month, year, hour, minute and second in the other columns. FullDateTime is every five minutes and I want to the DateTime to run for a whole year. I imagine the code to look something like:
Sub Func()
Dim 5mindays as Integer = 12*24*365
Dim x As Integer
Dim date
Dim time
For x = 1 To 5mindays
Split(," ")
Split(,"/")
Split(,":")
.Offset(0,1) = date(0)
...
.Offset(0,8) = time(2)
Add the next FullDateTime field below the existing one (adding 5 minutes)
Next
But have no idea how to actually do it. Please give me some ideas on how to solve this. Thanks!
Try after setting the correct worksheet name and year to process,
Option Explicit
Sub funk()
Dim dt As Long, yr As Long, tm As Long, dttm As Double
yr = 2018
dt = DateSerial(yr, 1, 1)
With Worksheets("sheet6")
Do While Year(dt) = yr
Do While TimeSerial(0, tm * 5, 0) < 1
dttm = dt + TimeSerial(0, tm * 5, 0)
.Cells(tm + 1 + (dt - DateSerial(yr, 1, 1)) * 288, "A").Resize(1, 9) = _
Array(dttm, dt, dttm - dt, _
Day(dt), Month(dt), yr, _
Hour(dttm), Minute(dttm), 0)
tm = tm + 1
Loop
tm = 0
dt = dt + 1
Loop
With .Range(.Cells(1, "A"), .Cells(.Rows.Count, "I").End(xlUp))
.Columns("A").NumberFormat = "dd/mm/yyyy hh:mm:ss AM/PM"
.Columns("B").NumberFormat = "dd/mm/yyyy"
.Columns("C").NumberFormat = "hh:mm:ss"
.Columns("D:I").NumberFormat = "0"
End With
End With
End Sub

How to convert Date Time to just Time?

I have a column of date time. I have to remove the date part. I simple want to run a macro that will do that. WHen I record macro, do the delete and then stop, then run it on the next row, it gives the value below. How does one globalize so I can run on all rows this task?
2017-06-26 14:41:00
the macro is this:
Sub Macro9()
'
' Macro9 Macro
'
'
ActiveCell.FormulaR1C1 = "2:41:00 PM"
ActiveCell.Offset(1, 0).Range("A1").Select
End Sub
Here is a simple macro to accomplish what you are looking to do. I assumed that you wanted to convert from military time to AM/PM. You will have to adjust the locations of cells to fit your spreadsheet. This is just going through all of the values in column A and turning them into just AM/PM time and spitting them out in coulmn B. Instead of looping through all of the rows you could also define your own single input function with the same logic.
Sub test()
Dim dt As String
Dim tm As String
Dim hr As String
Dim row_ct As Integer
row_ct = Range("A1").End(xlDown).Row
For i = 1 To row_ct
dt = Cells(i, 1)
tm = Right(Cells(i, 1), 8)
hr = Left(tm, 2)
If hr < 12 Then
tm = tm & " AM"
ElseIf hr = 12 Then tm = tm & " PM"
ElseIf hr > 12 and hr - 12 < 10 then tm = 0 & (Left(tm, 2) - 12) & Right(tm, 6) & " PM"
Else: tm = left(tm, 2) - 12 & right(tm, 6) & " PM"
End If
Cells(i, 2) = tm
Next i
End Sub
Here is how you can make a custom function that handles this:
Function tm(date_time)
If Left(Right(date_time, 8), 2) < 12 Then
tm = Right(date_time, 8) & " AM"
ElseIf Left(Right(date_time, 8), 2) = 12 Then tm = Right(date_time, 8) & " PM"
ElseIf Left(Right(date_time, 8), 2) > 12 Then tm = Left(Right(date_time, 8), 2)- 12 & Right(date_time, 6) & " PM"`
End If
End Function
Depending on the application, one will probably work better than the other.

write a basic formula in VBA code for Excel (string date text to date format)

Our accounting software exports dates as 07262013 as text. To convert this string of text to date format, I normally type the formula
=IF(A2>10000000,DATE(VALUE(RIGHT(A2,4)),VALUE(LEFT(A2,2)),VALUE(MID(A2,3,2))),
DATE(VALUE(RIGHT(A2,4)),VALUE(LEFT(A2,1)),VALUE(MID(A2,2,2))))
each time I export data. I want to write a custom function as =convert_text(text) to complete the same function.
I came up with
Function Convert_Date(text)
If text > 10000000 Then
Convert_Date = Application.Date(Application.Value(Application.Right(text, 4)), Application.Value(Application.Left(text, 2)), Application.Value(Application.Mid(text, 3, 2)))
Else
Convert_Date = Application.Date(Application.Value(Application.Right(text, 4)), Application.Value(Application.Left(text, 1)), Application.Value(Application.Mid(text, 2, 2)))
End Function
Thank you so much in advance!
Lee
You are looking for the following:
Function Convert_Date(text)
' assuming text is of the form mmddyyyy
' or mddyyyy
Dim year As Integer, month As Integer, day As Integer, L As Integer
L = Len(text)
year = Val(Right(text, 4))
day= Val(Mid(text, L - 5, 2))
If L = 7 Then month= Left(text, 1) Else month= Left(text, 2)
' >>>>> the next line is there for debugging;
' >>>>> take it out once you are happy with the result
MsgBox "year: " & year & "; month: " & month & "; day: " & day
Convert_Date = DateSerial(year, month, day)
End Function
This returns the "date serial number". You then format the cell with the date format you want, and you're good to go. Note that using explicit extraction of year, month, day makes the code much more readable.
Note - if you wanted to be more general, you could specify the format as an optional second string; e.g. ddmmyyyy in which case you could search for these characters and use that to extract the date properly:
Function Convert_Date(text, Optional formatString)
' assuming text is of the form mmddyyyy
' alternatively specify the format with the second parameter
Dim L As Integer, ii As Integer
Dim yearString As String, monthString As String, dayString As String
If IsMissing(formatString) Then formatString = "ddmmyyyy"
L = Len(text)
For ii = 1 To L
c = Mid(formatString, ii, 1)
t = Mid(text, ii, 1)
If c = "d" Then dayString = dayString & t
If c = "m" Then monthString = monthString & t
If c = "y" Then yearString = yearString & t
Next ii
Convert_Date = DateSerial(Val(yearString), Val(monthString), Val(dayString))
End Function
=DATE(YEAR(A1),MONTH(A1),DAY(A1))
no need! its already there :) if you need to do this in a fx it could look like this
function convert_date(text As String) As Date
convert_date = EVALUATE("DATE(YEAR(text),MONTH(text),DAY(text))")
end function
quickest i can think of is
Public Function FUNNYDATE(text As String) As Date
Dim padded As String
padded = Format(text, "00000000")
FUNNYDATE = DateSerial(Right(padded, 4), Left(padded, 2), Mid(padded, 3, 2))
End Function
Also, not that you do but in case it comes up in certain suggested solutions, I would steer clear of using DATEVALUE("mm-dd-yyyy") as its result depends on the locale of the user. Always stick to DATESERIAL(year,month,day)

Resources