How to get Month from Date? - excel

I'm trying to get a month from a cell that contains a date? I'm trying to do the following. But it throws a Run-time error #13 that the types don't match. How would you go about doing this, I've tried many solutions but it just doesn't work.
In my stylesheet I have this where I put start and end values and have blank spaces for the Macro to write in
Sub Search()
Dim accountTxt As String
Dim propertyTxt As String
Dim startMonth As Integer
Dim endMonth As Integer
Dim iAccount As String
Dim iProperty As String
Dim acum As Integer
Dim rowMonth As Integer
accountTxt = ActiveSheet.Cells(2, 17).Text
propertyTxt = ActiveSheet.Cells(3, 17).Text
startMonth = ActiveSheet.Cells(5, 17).Value
endMonth = ActiveSheet.Cells(6, 17).Value
For i = 1 To 800
iAccount = ActiveSheet.Cells(i, 8).Value
iProperty = ActiveSheet.Cells(i, 7).Value
rowMonth = Month(ActiveSheet.Cells(i, 1).Value)
If rowMonth >= startMonth And rowMonth <= endMonth Then
If InStr(1, iAccount, accountTxt) Then
Cells(i, 12).Interior.ColorIndex = 4
acum = acum + Cells(i, 12).Value
End If
End If
Next i
Cells(8, 17).Value = acum
End Sub

Say we have something in B9 like:
It may be a real date or just a string that looks like a date. In either case:
Sub PerhapsADate()
Dim s As String, MonthAsNumber As Long
Dim MonthAsString As String
s = Range("B9").Text
MonthAsNumber = --Split(s, "/")(0)
MonthAsString = Format(CDate(s), "mmmm")
MsgBox MonthAsNumber & vbCrLf & MonthAsString
End Sub
will get the month as both a number or a string:

To parlay off of Gary's Student's answer:
Sub PerhapsADate()
Dim s As Date, MonthAsNumber As Long
Dim MonthAsString As String
s = Range("B9").Text
MonthAsNumber = DatePart("m", s)
MonthAsString = Format(s, "mmmm")
MsgBox MonthAsNumber & vbCrLf & MonthAsString
End Sub
This solution differs slightly in that typing "s" as a date forces the text to be recognized as a date and therefore will be less prone to failure where international date format standards vary.

I got a type mismatch because the iterator starts reading the Date column at the "Date" heading and not the date value (e.g. 01-10-2017)

Related

VBA Excel: comparison of dates under different locale settings

I have a column in "dd-mm-yy hh:mm" format that formed as a result of some action on UserForm:
Dim ws as Worksheet
Set ws = Worksheets("Logs")
With ws
For i = 1 to Me.ListBox1.ListCount - 1
.Cells(lRow + 1 + i, 10).Value = CDate(VBA.Format(Me.ListBox1.List(i), "dd-mm-yy hh:mm"))
Next i
End With
I save the column to Variant variable to use later (to be used multiple times):
Dim arrTimeD As Variant
arrTimeD = Application.Transpose(.Range(TCL & "2:" & TCL & lRow).Value)
The locale date settings are European: "dd-mmm-yyyy"
The spreadsheet are used by different users, some have "dd-mmm" setting, others "mm-dd" etc.
I need to compare the dates in several uses. For, e.g.
Dim bDate as Date
bDate = CDate(VBA.Format(Me.lblCheckin.Caption,"dd-mm-yyyy"))
Do While CDate(arrTimeD(bIndex)) < bDate
If bIndex = lRow - 1 Then Exit Do
bIndex = bIndex + 1
Loop
When the user with US locale ("mm-dd") uses the spreadsheet, CDate(arrTimeD(bIndex)) throws error. CDate(VBA.Format(arrTimeD(bIndex))) and CDate(DateValue(arrTimeD(bIndex)) didn't help. What is the best way to do it?
Is it possible to set workbook's own date setting regardless of OS's?
Or I need to convert variant to string then concatenate?
The date string should be converted into a numeric date value.
Function DDMMYYYFormatToDateTimeValue(DateString As String) As Date
Dim Parts() As String
Parts = Split(DateString, "-")
DDMMYYYFormatToDateTimeValue = CDate(Parts(1) & "/" & Parts(0) & "/" & Parts(2))
End Function
Usage
Private Sub UserForm_Initialize()
Dim n As Long
For n = 1 To 100
ListBox1.AddItem Format(Date + n / 24, "MM-DD-YY HH:MM")
Next
End Sub
Public Function ListBoxDateValues()
Dim Data As Variant
ReDim Data(1 To Me.ListBox1.ListCount, 1 To 1)
Dim DateString As String
Dim r As Long
For r = 1 To Me.ListBox1.ListCount
DateString = Me.ListBox1.List(r - 1)
Data(r, 1) = DDMMYYYFormatToDateTimeValue(DateString)
Next
ListBoxDateValues = Data
End Function
Public Function wsLogs() As Worksheet
Set wsLogs = ThisWorkbook.Sheets("Logs")
End Function
Function DDMMYYYFormatToDateTimeValue(DateString As String) As Date
Dim Parts() As String
Parts = Split(DateString, "-")
DDMMYYYFormatToDateTimeValue = CDate(Parts(1) & "/" & Parts(0) & "/" & Parts(2))
End Function
First, true date values carry no format, so convert your text dates from the listbox directly to true date values:
.Cells(lRow + 1 + i, 10).Value = CDate(Me.ListBox1.List(i))
These you can apply the format you prefer for display.
The comparison is now straight:
Dim bDate As Date
bDate = CDate(Me.lblCheckin.Caption)
Do While arrTimeD(bIndex) < bDate
If bIndex = lRow - 1 Then
Exit Do
Else
bIndex = bIndex + 1
End If
Loop

VBA - Change date in excel from datetime to mm/dd/yy (change to string datatype, not just the cosmetic format)

I'm trying to populate a date from a data source in which the date is formatted as datetime. The destination file can only accept the mm/dd/yy format to upload to our system, but everything that I try is either only cosmetically formatting the date (i.e. datetime still shows in the formula bar) or converts the data to m/d/yyyy which also won't work.
Below is what I've tried, with no success:
Via VBA (only cosmetically changes the format):
[T:T].Select
With Selection
.NumberFormat = "mm/dd/yy"
.Value = .Value
End With
Using VBA to create a temporary helper column U with the below formula (gets me to m/d/yyyy:
=MONTH(T2)&"/"&DAY(T2)&"/"&YEAR(T2)
I know that I can create a bunch of conditional statements to make the above work, but was curious if there was a less convoluted way to solve what seems like a very simple problem.
Edit: To be clear, the result will likely have to be stored as a string.
Per Scott Craner's advice, the following loop worked perfectly!
For i = 2 To LastRow
Range("T" & i).NumberFormat = "#" 'Format as text to prevent excel from taking over
Range("T" & i) = Format(Range("T" & i), "mm/dd/yy")
Next i
Try
Sub test()
Dim rngDB As Range
Dim vDB
Dim i As Long, r As Long
Set rngDB = Range("t1", Range("t" & Rows.Count).End(xlUp))
vDB = rngDB
r = UBound(vDB, 1)
For i = 1 To r
vDB(i, 1) = Format(vDB(i, 1), "mm/dd/yy")
vDB(i, 1) = Replace(vDB(i, 1), "-", "/")
Next i
rngDB.NumberFormatLocal = "#"
rngDB = vDB
End Sub
Try forcing the NumberFormat to text. Here is an example.
Option Explicit
Sub SetDateTime()
Dim lngRow As Long
For lngRow = 1 To 10
Cells(lngRow, 20).Value = Now
Next lngRow
End Sub
Sub ReformatDate()
Dim lngRow As Long
Dim datX As Date
Dim strX As String
For lngRow = 1 To 10
strX = Cells(lngRow, 20).Value
If IsDate(strX) Then
datX = CDate(strX)
Cells(lngRow, 20).NumberFormat = "#"
Cells(lngRow, 20).Value = Format(datX, "mm/dd/yy")
End If
Next lngRow
End Sub

EXCEL VBA TYPE MISMATCH (13) TIME STAMP DIFFERENCE

Excelfile
Hello I have an excel files with time stamps in a row as shown in the image
I want to calculate the difference and enter the value in a new column. I tried the following code but it shows a type mismatch error and I don't know why.
I know its easy, but I'm new to VBA so please help me.
\\Sub macro1()
Dim i As Integer
Dim j As Integer
Dim k As Integer
i = 1
j = 2
k = 2
Do While Cells(i, 1).Value <> ""
Cells(k, 2).Value = Cells(j, 1).Value - Cells(i, 1).Value
i = i + 1
j = i + 1
k = i
Loop
End Sub
Your format (2.10.2017 08:08:30) should be manipulated before using CDate to convert the cell value into a date, then use the VBA function DateDiff. See below. Put =timeDiff(A2,A1) in B2, then copy to B3 and down. Below is the VBA code.
Public Function transformCellStrInDate(ByVal rng As Range) As Date
Dim splitArr As Variant, dateArr As Variant, dateStr As String
splitArr = Split(Trim(rng.Value))
dateArr = Split(splitArr(0), ".")
dateStr = dateArr(0) & "/" & dateArr(1) & "/" & dateArr(2) & " " & splitArr(1)
transformCellStrInDate = CDate(dateStr)
Erase dateArr: Erase splitArr
End Function
Public Function timeDiff(ByVal rngY As Range, ByVal rngX As Range) As Long
timeDiff = DateDiff("n", transformCellStrInDate(rngX), transformCellStrInDate(rngY)) / 60 ' in Hours
End Function

Leading zero vba excel wrong dates

I have this dates from DB and I want to fix the date in VBA excel because excel switch the date with month when filter the column
27/08/2018
31/08/2018
12/9/2018
2/8/2018 wrong date reported at filter in excel need 02/08/2018
6/8/2018 wrong date reported at filter in excel need 06/08/2018
13/08/2018
17/08/2018
20/08/2018
20/08/2018
I have tried this
For i = 2 To lastRow
Dim fDate As Date
Dim dayF As String
Dim monthF As String
Dim yearF As String
Set r = Cells(i, Column_DateStamp)
strDate = Split(r.Text, "/")
dayF = CStr(Format(strDate(0), "00"))
monthF = CStr(Format(strDate(1), "00"))
yearF = CStr(Format(strDate(2), "0000"))
fDate = Format(DateSerial(strDate(2), CStr(Format(strDate(1), "00")), CStr(Format(strDate(0), "00"))), "dd/mm/yyyy")
r.Clear
r.Value = fDate
Next i
The date formats do not match your local date format and as such Excel is trying to convert.
You need to either put the date in and format it appropriately or make the cell text so excel does not try to convert.
Dim i As Long
For i = 2 To lastRow
Dim fDate As Date
Dim r As Range
Set r = Cells(i, Column_DateStamp)
strDate = Split(r.Text, "/")
fDate = DateSerial(strDate(2), strDate(1), strDate(0))
r.Clear
'True date - comment out if you want string
r.NumberFormat = "dd/mm/yyyy"
r.Value2 = fDate
'String - Uncomment if you want string
' r.NumberFormat = "#"
' r.Value2 = Format(fDate, "dd/mm/yyyy")
Next i
Examining your screenshot, the problem is consistent with your Windows Regional Settings being MDY and the Database settings being DMY. This will always result in incorrect action by Excel.
Whoever wrote the ERP application should be able to make the change to input, to Excel, an unambiguous date format; or trigger the excel text import wizard at the time of import.
You can try this macro in the meantime. It should work, but read the notes carefully for possible pitfalls:
Option Explicit
Sub ConvertDates()
'converts dates that have been mismatched MDY / DMY
'Assumes dates are all in selected column
' Only need to select a single cell in the column
' will place results in a column next to original data
' If adjacent column is not blank, a column will be inserted
'Figures out the original format by analyzing a "text" date
'Time components are converted directly. This might be OK unless
' in a non standard format such as 1400Z
Dim R As Range, C As Range
Dim sDelim As String
Dim FileDateFormat As String * 3
Dim i As Long, j As Long, V As Variant
Dim vDateParts As Variant
Dim YR As Long, MN As Long, DY As Long
Dim TM As Double
Dim vRes As Variant 'to hold the results of conversion
Set R = Selection
'Test that selected cell contains a date
If Not IsDate(R(1)) Then
MsgBox "Select a cell containing a date"
Exit Sub
End If
Set R = Intersect(R.EntireColumn, ActiveSheet.UsedRange)
ReDim vRes(1 To R.Rows.Count, 1 To 1)
'Find a "text date" cell to analyze
For Each C In R
With C
If IsDate(.Value) And Not IsNumeric(.Value2) Then
'find delimiter
For i = 1 To Len(.Text)
If Not Mid(.Text, i, 1) Like "#" Then
sDelim = Mid(.Text, i, 1)
Exit For
End If
Next i
'split off any times
V = Split(.Text & " 00:00")
vDateParts = Split(V(0), sDelim)
If vDateParts(0) > 12 Then
FileDateFormat = "DMY"
Exit For
ElseIf vDateParts(1) > 12 Then
FileDateFormat = "MDY"
Exit For
Else
MsgBox "cannot analyze data"
Exit Sub
End If
End If
End With
Next C
If sDelim = "" Then
MsgBox "cannot find problem"
Exit Sub
End If
'Check that analyzed date format different from Windows Regional Settings
Select Case Application.International(xlDateOrder)
Case 0 'MDY
If FileDateFormat = "MDY" Then
MsgBox "File Date Format and Windows Regional Settings match" & vbLf _
& "Look for problem elsewhere"
Exit Sub
End If
Case 1 'DMY
If FileDateFormat = "DMY" Then
MsgBox "File Date Format and Windows Regional Settings match" & vbLf _
& "Look for problem elsewhere"
Exit Sub
End If
End Select
'Process dates
'Could shorten this segment but probably more understandable this way
j = 0
Select Case FileDateFormat
Case "DMY"
For Each C In R
With C
If IsDate(.Value) And IsNumeric(.Value2) Then
'Reverse the day and the month
YR = Year(.Value2)
MN = Day(.Value2)
DY = Month(.Value2)
TM = .Value2 - Int(.Value2)
ElseIf IsDate(.Value) And Not IsNumeric(.Value2) Then
V = Split(.Text & " 00:00") 'remove the time
vDateParts = Split(V(0), sDelim)
YR = vDateParts(2)
MN = vDateParts(1)
DY = vDateParts(0)
TM = TimeValue(V(1))
Else
YR = 0
End If
j = j + 1
If YR = 0 Then
vRes(j, 1) = C.Value
Else
vRes(j, 1) = DateSerial(YR, MN, DY) + TM
End If
End With
Next C
Case "MDY"
For Each C In R
With C
If IsDate(.Value) And IsNumeric(.Value2) Then
'Reverse the day and the month
YR = Year(.Value2)
MN = Day(.Value2)
DY = Month(.Value2)
TM = .Value2 - Int(.Value2)
ElseIf IsDate(.Value) And Not IsNumeric(.Value2) Then
V = Split(.Text & " 00:00") 'remove the time
vDateParts = Split(V(0), sDelim)
YR = vDateParts(2)
MN = vDateParts(0)
DY = vDateParts(1)
TM = TimeValue(V(1))
Else
YR = 0
End If
j = j + 1
If YR = 0 Then
vRes(j, 1) = C.Value
Else
vRes(j, 1) = DateSerial(YR, MN, DY) + TM
End If
End With
Next C
End Select
With R.Offset(0, 1).EntireColumn
Set C = .Find(what:="*", LookIn:=xlFormulas)
If Not C Is Nothing Then .EntireColumn.Insert
End With
R.Offset(0, 1).Value = vRes
End Sub

Excel Split() converting number to Date

I am trying to implement a SPLIT() function to parse a string in EXCEL and distribute the result to adjacent cells on the same form. The following is working as expected, except when a parsed term is a Number.
"0.25" parses to "1/0/1900 6:00:00 AM"
I tried cstr() on the resulting strAttr value, but seems to have no effect. Any ideas?
Sub splitText()
Dim i As Integer
Dim x As Integer
Dim strText As String
Dim strAttr As Variant
Dim strFirst As String
Dim NumRows As Integer
strFirst = "A4"
Sheets("Data").Activate
Range(strFirst).Select
NumRows = Range(strFirst, Range(strFirst).End(xlDown)).Rows.Count
For x = 1 To NumRows
ActiveCell.Offset(1, 0).Select
strText = ActiveCell.Value
strAttr = Split(strText, " ")
For i = 0 To UBound(strAttr)
Cells(x + 4, i + 2).Value = strAttr(i)
Next i
Next
End Sub
Note:
I forced a (') to the front of the string, which seems to provide the desired result, except everything will be = TEXT:
For i = 0 To UBound(strAttr)
Cells(x + 4, i + 2).Value = "'" & strAttr(i)
Next i
Is there a better way to accomplish this and retain "0.25" as a Number value?
Thanks,
mark
This may help. Replace:
strText = ActiveCell.Value
with:
strText = ActiveCell.Text

Resources