Run-time Error '6' Overflow when storing date in var - excel

I am iterating through dates in a loop to execute different snippets of code.The following piece of code in the loop gives me a
runtime error '6' Overflow
when assigning the cell's value to dateClaim:
Dim dateClaim As Date
Dim rngDateClaimeMade As Range
Set rngDateClaimeMade = dfensCSheet.Range("AC7") 'AC contains dates in format dd.mm.yyyy
dateClaim = rngDateClaimeMade.value
dateClaimMonth = Format(Month(dateClaim), "00")
dateClaimYear = Year(dateClaim)
Any ideas/ help is very much appreciated!

So that looks like 24.12.2020 is a text not a date in that cell and therefore it cannot be converted automatically.
If your dates are always in this format dd.mm.yyyy you can convert it like below:
Option Explicit
Public Sub Example()
Dim TextDate As String ' this is a text looking like a date (but is not a date just a string)
TextDate = "24.12.2020" ' instead read your cell value here
' test if the string has a format that we can convert
If Not TextDate Like "??.??.????" Then
MsgBox "Date was not in expected format dd.mm.yyyy"
Exit Sub
End If
' split text into 3 parts by dot as delimiter
Dim SplitDate() As String
SplitDate = Split(TextDate, ".")
' reorder the 3 parts to make a real numeric date
Dim NumericDate As Date
NumericDate = DateSerial(SplitDate(2), SplitDate(1), SplitDate(0))
' this numeric date is now a real date that can be formatted as desired
Debug.Print Format$(NumericDate, "yyyy-mm-dd") 'returns 2020-12-24
End Sub
You can then use
Dim dateClaim As Date
dateClaim = DateSerial(SplitDate(2), SplitDate(1), SplitDate(0))
Dim dateClaimMonth As String
dateClaimMonth = Format$(dateClaim , "mm")
Dim dateClaimYear As String
dateClaimYear = Format$(dateClaim , "yyyy")
if you need month and year as text! If you need them numeric don't use Format$()!

VBA cannot convert text dates with dots directly. So try:
dateClaim = DateValue(Replace(rngDateClaimeMade.Value, ".", "/"))
dateClaimMonth = Month(dateClaim)
dateClaimYear = Year(dateClaim)
Apply the format 00 where the month is to be displayed.

Related

CDATE VBA gives out 12:00:00 AM instead of date

I am trying to convert the date format of my cells as the csv format they are delivered in shows a date but excel doesn't recognize it as a date (it shows "Standard" as format and the dates are aligned on the left, hence not dates in excel).
Dim lr11 As Integer
Dim dates11 As Date
lr11 = WS1.Cells(WS1.Rows.Count, "C").End(xlUp).row
For dates11 = 2 To lr11
WS1.Cells(dates11, 3).Value = CDate(Cells(dates11, 3).Value)
Next dates11
The above code sometimes works in a Test Sub() but when used in my main Sub, I always get "12:00:00 AM" in all cells instead of dates.
What am I doing wrong?
Thanks!
If you have strings that look like dates in the format DD.MM.YYYY you can split them and create a numeric date using DateSerial like below:
Option Explicit
Public Function ConvertStringDDMMYYYYtoDate(ByVal InputString As String) As Date
Dim RetVal As Date
Dim Parts() As String
Parts = Split(InputString, ".")
If UBound(Parts) = 2 Then
RetVal = DateSerial(Parts(2), Parts(1), Parts(0))
If Not Format$(RetVal, "DD.MM.YYYY") = InputString Then
MsgBox "Input String is not a real date", vbCritical
RetVal = 0
End If
End If
ConvertStringDDMMYYYYtoDate = RetVal
End Function
Then use it like
For dates11 = 2 To lr11
WS1.Cells(dates11, 3).Value = ConvertStringDDMMYYYYtoDate(WS1.Cells(dates11, 3).Value)
WS1.Cells(dates11, 3).NumberFormat = "DD.MM.YYYY" ' format it however you like it to look like
Next dates11

How to display sub string in reverse order but read from left to right in VBA

I am processing a .txt file in VBA.
Amongst other tasks, I need to read in a string representing a date and display the actual date in Excel.
A date string in the .txt file looks like "190223"
This represents 23/02/2019
My challenge is to get this done.
What I have done so far is:
' ... loop
With ActiveWorkbook.Worksheets(1)
' Other statements here
' Event date time
.Range("N" & i).Value = StrReverse(Mid(.Range(keyword.Offset(0, 4).Address), 1, 2) & _
"/" & Mid(.Range(keyword.Offset(0, 4).Address), 3, 2) & _
"/" & Mid(.Range(keyword.Offset(0, 4).Address), 5, 2))
End With
But I get the undesired output:
32/20/91 ' For a date string 190223 the desired output should be 23/02/19
Any help would be much appreciated.
Thanks in advance.
Convert it into a real date
You must extract year, month and day of that string and then convert this into a real date.
Then you can format the date to what ever date format you like. The value that is saved in the cell is then a real date value (not a string!) so you can calculate with it.
I highly recommend to read How Dates Work in Excel – The Calendar System Explained + Video to understand the background and why real dates are so important.
Here is an example:
Option Explicit
Public Sub ConvertDateExample()
Const InputStr As String = "190223"
Dim InputYear As Integer
Dim InputMonth As Integer
Dim InputDay As Integer
'extract year, month and day
InputYear = Left(InputStr, 2)
InputMonth = Mid(InputStr, 3, 2)
InputDay = Right(InputStr, 2)
'put it together to a real date
Dim RealDate As Date
RealDate = DateSerial(InputYear, InputMonth, InputDay)
'write the date into a cell
Range("A1").Value = RealDate
'format that cell to your desired format
Range("A1").NumberFormat = "dd/mm/yyyy"
End Sub

Formatting a number to two digits even if the first is a 0 vba

I would like to be able to use VBA to display any number between 1-24 as a 2 digit number. Obviously the only ones that have a problem with this are 1-9 which I would like displayed as 01, 02, 03, etc. Is there a way to perform this?
You cannot format an integer variable, you need to use a string variable for formatting.
You can convert the day part of a date to a format with leading zeros using the Day function to extract the day number from the date, and then using the Format function with a "00" format to add a leading zero where necessary
Format(Day(myDate), "00")
myDate is a Date variable containing the full Date value
The following macro can be used as a working sample
Sub Macro1()
Dim myDate As Date
myDate = "2015-5-1"
Dim dayPart As String
dayPart = Format(Day(myDate), "00")
MsgBox dayPart
End Sub
Sure you can format an integer, you just convert it to string within the format command:
formattedIntAsString = Format(Cstr(intValue), "00")
I did it like this:
number_item = 2
number_item = WorksheetFunction.Text(number_item, "00")
This will do the job.
I know it's old, but, to answer the question as clarified, I would use in the built in date formatting functionality.
To modify DeanOC's answer:
Sub Macro1()
Dim dateDate As Date
Dim strDate As String
Dim strDay As String
dateDate = "2015-5-1"
strDate = Format(dateDate, "mm/dd/yy") ' = "05/01/15"
strDay = Format(dateDate, "dd") ' = "01"
MsgBox "The two digit day of """ & strDate & """ is """ & strDay & ""."
End Sub

String to Date, Accessing date only from Now function

I have the date and time in the following format:
7/12/2012 3:41
I want to keep only the date from this. I have tried to write a function to do this, but excel will only recognise this as a string so I am having difficulty editing the entry. If some one could help me with a function or direction to spilt off only the date portion of this it would be greatly appreciated.
My intended application is something along the lines of
Public Function Change(X As Variant)
'
If X > Application.WorksheetFunction.Now() Then
Change = 1
End If
'
End Function
Depends whether you are looking for a Date or a String as the output. Here's how to do both.
Dim strDateTime As String
Dim strDate As String
Dim s() As String
Dim pureDate As Date
strDateTime = "7/12/2012 3:41"
strDate = Split(strDateTime, " ")(0) ' "7/12/2012"
pureDate = CDate(strDate) ' 7 Dec 2012 (in my locale)
' ... results may be ambiguous depending on your locale
'Another way to get a Date, not blindly using CDate:
s = Split(strDate, "/")
' if date in day/month/year format:
pureDate = DateSerial(CInt(s(2)), CInt(s(1)), CInt(s(0))) ' 7 Dec 2012
' or, if date in month/day/year format:
pureDate = DateSerial(CInt(s(2)), CInt(s(0)), CInt(s(1))) ' 12 July 2012
Use the Format function like this:
Public Function Change(DateExp) As Date
'Format function lets you transform most data in your desired format.
'CDate handles any Date Expression conversion to Date data type.
'CStr handles any expression conversion to String data type
If IsMissing(ReturnType) Then
'Return as Date, default when ReturnType is not supplied
Change = Format(CDate(DateExp), "m/d/yyyy")
Else
If ReturnType = True Then
'Return as Date
Change = Format(CDate(DateExp), "m/d/yyyy")
ElseIf ReturnType = False Then
Change = Format(CDate(DateExp), "m/d/yyyy")
'Return as String
Change = CStr(Change)
Else
'Error out any values other than TRUE or FALSE
Change = CVErr(xlErrValue)
End If
End If
End Function
But if you are really interested with returning just the date, use Today() Function instead of Now() (for WS).
Equivalent functionality in VBA is Date Function which return your systems current date.
Same

VB6, CDate(sheet.range("B", counter))

I've been looking and looking for a solution but without success.
I need to populate list-view by date criteria, I know how to fill it with simple criteria but date criteria has given me a lot of problems.
I have dates (dd.mm.yyyy) in B column in my Excel document and I need to convert them to date and compare with date which I choose from calendar control on the form. How can I set that default date in VB6 be dd.mm.yyyy?
I am beginner and I don't know where I am wrong, please help me. Thanks in advance.
Do Until .Cells(myCounter, 1) & "" = ""
strDate = listObj.Range("B" & myCounter)
myDate= CDate(strDate) >>>>>>>>>> Run-time error "13" Mismatch type
If myDate > Calendar1.Value Then
.........................
End If
myCounter =myCounter + 1
Loop
edit: This is my whole code
Dim excelObj As excel.Application
Dim wbObj As excel.Workbook
Dim sheetObj As Worksheet
Dim myCounter As Long
Set excelObj = New excel.Application
excelObj.Visible = False
Set wbObj = excelObj.Workbooks.Open(App.Path & "\excel_document.xlsx")
Set sheetObj = excelObj.Worksheets("Sheet1")
Dim L As ListItem
Dim myDateAs Date
Dim strDate As String
ListView1.ListItems.Clear
With sheetObj
myCounter = 2
Do Until .Cells(myCounter, 1) & "" = ""
strDate = sheetObj.Range("B" & myCounter)
myDate= CDate(strDate)
If myDate > Calendar1.Value Then
........
End If
myCounter = myCounter + 1
Loop
End With
excelObj.Quit
In excel document B column is formatted as Date - dd/mm/yyyy. I tried also not to do CDate but without success.
How did you declare strDate? Dim strDate As String? Variant? Not declared?
Given what you're trying to do, it really should be declared as either Variant or Date. It looks like you declared it as a String, and that you are also entering strings on the cells.
When you Enter the date values in Excel, you should enter them as dates instead of strings. It's easy; just make sure that the cells are formatted with "dd.mm.yyyy" and they will accept such dates correctly when you type them. When you retrieve the values from VB, they will be retrieved as Dates and you will be able to manipulate them as such.
If you really want to transform a string that comes in that format into a Date value, you can use this method: Parse finnish date string to Date Type in VB6

Resources