Vba excel сравнение двух дат

 

Всем ДД.  
Маленький кусочек кода  
a = Range(«B4»)  
If a < «15.07.2005» Then  

  в «В4» число в формате даты 12.07.2005  
Как это правильно записать?  
и, заодно, какой тип задать переменной А?  
Dim A As ?  
Спасибо.

 

KuklP

Пользователь

Сообщений: 14868
Регистрация: 21.12.2012

E-mail и реквизиты в профиле.

Здравствуй, Миш.  
dim a as date  
a = Range(«B4»)  
If a < CDate(«15.07.2005») Then …

Я сам — дурнее всякого примера! …

 

Юрий М

Модератор

Сообщений: 60575
Регистрация: 14.09.2012

Контакты см. в профиле

ДВ! Тоже экономлю :-)  
Dim a as Date, b as Date  
А по первой части не очень понял — с датами обычная работа при сравнении (это ведь числа):  
If a < b Then

 

Немного не точно написал.    
a = Range(«B4:B6»)  
as date выдает ошибку… только as variant ?

 

Юрий М

Модератор

Сообщений: 60575
Регистрация: 14.09.2012

Контакты см. в профиле

Range(«B4:B6») — это уже диапазон :-) Что за данные там? Может файл?

 

KuklP

Пользователь

Сообщений: 14868
Регистрация: 21.12.2012

E-mail и реквизиты в профиле.

{quote}{login=Михаил}{date=28.02.2011 07:44}{thema=}{post}Немного не точно написал.    
a = Range(«B4:B6»)  
as date выдает ошибку… только as variant ?{/post}{/quote}  
Если указываешь диапазон,  то а будет массив значений. тогда циклом cdate(a(i)) сравнивай.

Я сам — дурнее всякого примера! …

 

В диапазоне только даты — (сам сейчас заполняю, автоподстановкой).  
Юр, ну можно, конечно, написать в коде    
If a < 46000 Then (например), но хочется, что б и наглядность была  
:)

 

KuklP

Пользователь

Сообщений: 14868
Регистрация: 21.12.2012

E-mail и реквизиты в профиле.

Вернее  
a(i,1)

Я сам — дурнее всякого примера! …

 

Про массив и цикл я понимаю. Просто не получалось сравнить  
А(2) > «01.03.2000» (к примеру)

 
 

Юрий М

Модератор

Сообщений: 60575
Регистрация: 14.09.2012

Контакты см. в профиле

{quote}{login=Михаил}{date=28.02.2011 07:51}{thema=}{post}Юр, ну можно, конечно, написать в коде    
If a < 46000 Then (например), но хочется, что б и наглядность была  
:){/post}{/quote}  
Про числа я совсем с другой стороны :-)  
В А1 — Сегодня  
If Range(«A1») < CDate(«01.03.2011») Then MsgBox «Меньше»

 

KuklP

Пользователь

Сообщений: 14868
Регистрация: 21.12.2012

E-mail и реквизиты в профиле.

Юра, Васмк представляет даты, как #12.07.2005#(можно увидеть в окне переменных). Вопрос, а как такой же формат использовать в коде? Не сталкивался? Собственно, вопрос не только к Юре. Если у кого мысли(или варианты) есть — давайте обсудим.

Я сам — дурнее всякого примера! …

 

KuklP

Пользователь

Сообщений: 14868
Регистрация: 21.12.2012

E-mail и реквизиты в профиле.

Флуд, конечно, глянул на три первые поста темы и мелькнуло — старперы собрались, доминошники(сам никогда ни в домино, ни в другие игры… мне интересны головоломки):-)  
С уважением, Сергей.

Я сам — дурнее всякого примера! …

 

Hugo

Пользователь

Сообщений: 23251
Регистрация: 22.12.2012

Привет, Сергей.  
Опередил меня, я точно такой код написал :)  
Я по поводу #12.07.2005#.  

  Dim a As Date, b As Date  
a = Range(«B4»)  
b = CDate(«15.07.2005»)  
If a < b Then MsgBox 1  

  Если так написать, то в Locals обе переменные одинаковы.

 

KuklP

Пользователь

Сообщений: 14868
Регистрация: 21.12.2012

E-mail и реквизиты в профиле.

{quote}{login=Hugo}{date=28.02.2011 08:32}{thema=}{post}Привет, Сергей.  
Опередил меня, я точно такой код написал :)…  
Я по поводу #12.07.2005#.  
{/post}{/quote}  
А кто сомневался:-)… А дальше? Как такой формат #12.07.2005# втюхать в код?

Я сам — дурнее всякого примера! …

 

Hugo

Пользователь

Сообщений: 23251
Регистрация: 22.12.2012

Не знаю… Я помню ту тему — тоже потыкался, так ничего не получилось…  
А здесь CDate(«15.07.2005»)=#15.07.2005#

 

Юрий М

Модератор

Сообщений: 60575
Регистрация: 14.09.2012

Контакты см. в профиле

Да, интересно… Вот, например, время я ввожу так:  
Public Const TimeStart = #12:00:00 AM#  
Т.е., решётка имеет место быть :-)

 

KuklP

Пользователь

Сообщений: 14868
Регистрация: 21.12.2012

E-mail и реквизиты в профиле.

{quote}{login=Юрий М}{date=28.02.2011 09:08}{thema=}{post}Да, интересно… Вот, например, время я ввожу так:  
Public Const TimeStart = #12:00:00 AM#  
Т.е., решётка имеет место быть :-){/post}{/quote}  
Ребят, да не парьтесь. Нет, так нет. Мы с вами легко решаем такие феньки без диезов. Т.е. дедушка Эксель прелагает  нам множество других путей.:-) Очень рад видеть вас на форуме!

Я сам — дурнее всякого примера! …

 

Kuzmich

Пользователь

Сообщений: 7998
Регистрация: 21.12.2012

Может быть так  
Dim d As Date  
Dim s As Single  
s=#1/3/2011#  
d=s

 

KuklP

Пользователь

Сообщений: 14868
Регистрация: 21.12.2012

E-mail и реквизиты в профиле.

Офигеть. Дело в разделителях. Какого же он в переменных показывает… Ну да, Locals… Kuzmich, спасибо! Короче, или никак, или с буржуйскими разделителями:-)

Я сам — дурнее всякого примера! …

 

Serge

Пользователь

Сообщений: 11308
Регистрация: 01.01.1970

{quote}{login=KukLP}{date=28.02.2011 09:15}{thema=Re: }{post}…дедушка Эксель прелагает  нам множество других путей…{/post}{/quote}Какой-же он дедушка, если ему только 26-й годик?

 

KuklP

Пользователь

Сообщений: 14868
Регистрация: 21.12.2012

E-mail и реквизиты в профиле.

Серег, все познается… А если сложить все года разработчиков, на него затраченные? Я помню еще Quattro, QuattroPro, Supercalc — где они сейчас? Так что Экс считаю уже умуденным сединами. И очень уважаю(можно даже сказать люблю). Думаю(зная тебя) и ты со мной спорить не станешь:-)

Я сам — дурнее всякого примера! …

 

Serge

Пользователь

Сообщений: 11308
Регистрация: 01.01.1970

Нет.  
Вопрос риторический был :-)

 

R Dmitry

Пользователь

Сообщений: 3103
Регистрация: 22.12.2012

Excel,MSSQL,Oracle,Qlik

#24

28.02.2011 23:54:10

ну и не забываем что формат всегда mm/dd/yyyy  

  :-)

Спасибо


You can use the following basic syntax in VBA to compare two dates:

Sub CompareDates()
    Dim i As Integer

    For i = 2 To 5
        If CDate(Range("A" & i)) < CDate(Range("B" & i)) Then
            Result = "First Date is Earlier"
    Else
        If CDate(Range("A" & i)) > CDate(Range("B" & i)) Then
                Result = "First Date is Later"
            Else
                Result = "Dates Are Equal"
            End If
        End If
        
    Range("C" & i) = Result
    
    Next i
End Sub

This particular example will compare the dates in the corresponding cells in the ranges A2:A5 and B2:B5 and return the result of the date comparisons in the range C2:C5.

Note: The CDate function converts the value in a given cell to a date.

The following example shows how to use this syntax in practice.

Example: Compare Dates in VBA

Suppose we have the following two columns with dates in Excel:

Suppose we would like to compare the dates in each corresponding row and output the results of the date comparison in column C.

We can create the following macro to do so:

Sub CompareDates()
    Dim i As Integer

    For i = 2 To 5
        If CDate(Range("A" & i)) < CDate(Range("B" & i)) Then
            Result = "First Date is Earlier"
    Else
        If CDate(Range("A" & i)) > CDate(Range("B" & i)) Then
                Result = "First Date is Later"
            Else
                Result = "Dates Are Equal"
            End If
        End If
        
    Range("C" & i) = Result
    
    Next i
End Sub

When we run this macro, we receive the following output:

The results of the date comparisons are now shown in column C.

Additional Resources

The following tutorials explain how to perform other common tasks in VBA:

VBA: How to Sort Sheet by Multiple Columns
VBA: How to Count Number of Rows in Range
VBA: How to Filter a Column


Apart from the excellent solution of Siddharth Rout at Formatting MM/DD/YYYY dates in textbox in VBA, I’ll suggest the following procedure. UserForm is a natural object in Excel, but we shall make reference to an OCX object to use it in Access, so not directly available.

In Access with form object, one can do this:

Sub sof20270928CompareDates()
  If CDate(txtRecievedDate.Value) < CDate(txtOrderDate.Value) Then
    MsgBox "Incorrect Date, item can't be recieved before order"
  Else
    MsgBox "correct date"
  End If
End Sub

Instead of comparing text strings, we compare now dates. CDate() converts local date time strings into date type. An American will type the date in mm/dd/yyyy format, like 11/19/2013, in France one types dd/mm/yyyy, like 19/11/2013. CDate() will take care of this as Access considers the computer’s locale.

Moreover, txtRecievedDate.Value is preferealbe to txtRecievedDate.Text, the latter requires focus, ie, the control must be active to get the .text property.

This example teaches you how to compare dates and times in Excel VBA. Dates and times are stored as numbers in Excel and count the number of days since January 0, 1900. What you see depends on the number format.

1. Enter some numbers in column A.

Numbers

2. These numbers are dates. This is a perfect way to enter some dates without worrying about the Date format. Change the format to Date (Right click on the column A header, Format Cells and choose Date).

Result:

Dates

Note: Dates are in US Format. Months first, Days Second. This type of format depends on your windows regional settings.

Place a command button on your worksheet and add the following code lines:

3. Declare the variable i of type Integer.

Dim i As Integer

4. Add a For Next loop.

5. The Date function returns the current date without the time. Add the following code line to the loop, to highlight all the cells containing the current date (3/13/2020).

If Cells(i, 1).Value = Date Then Cells(i, 1).Font.Color = vbRed

Result:

Dates Equal To

6. Add the following code line to the loop, to highlight all the dates earlier than 04/19/2019.

If Cells(i, 1).Value < DateValue(«April 19, 2019») Then Cells(i, 1).Font.Color = vbRed

Result:

Dates Earlier Than

7. But what about times, we hear you say. They are the decimals. Switch back to General format and change the numbers to decimal numbers.

Decimal Numbers

8. Now change the format to ‘Date and Time’ format.

Date and Time Format

Result:

Dates and Times

9. If you want to highlight all cells containing the current date, we cannot use the code line at 5 anymore. Why not? Because the numbers in column A are decimal numbers now. Comparing it with Date (a whole number) would not give any match. (It would only give a match with 3/13/2020 at midnight exactly!) The following code line does work:

If Int(Cells(i, 1).Value) = Date Then Cells(i, 1).Font.Color = vbRed

Explanation: we simply use the Int function. The Int function rounds a number down to the nearest integer. This way we can get the dates without the times and compare these dates with Date.

Result:

Dates Without Times Equal To

10. Add the following code line to highlight all the cells containing times in the morning.

If (Cells(i, 1).Value — Int(Cells(i, 1).Value)) < 0.5 Then Cells(i, 1).Font.Color = vbRed

Explanation: we only need the decimals so therefore we subtract the integer part. Noon (halfway through the day) is represented as 0.5. Decimals lower than 0.5 are the times in the morning.

Result:

Times in the Morning

If you’re working with dates in your excel sheets then you have to understand the date object. By using the date object you could easily process the dates on your excel sheets. You can compare dates to see which one is more recent, you can add and subtract a certain amount of days month, years to a specific date. You can get the current date ….

You can download the codes and files related to this article here.
Jump to:

  • DateSerial(), Creating Date Objects From Year, Month and Day Values
  • CDate(), Creating (Converting) Date Objects From Strings
  • IsDate(), Checking if String is a Date Expression
  • Comparing Dates, Recent, Older …
  • Getting The Year, Month and Day Values From A Date Object
  • Adding and Subtracting Years, Months and Days From Dates
  • Date(), Getting Current Date

DateSerial(), Creating Date Objects From Year, Month and Day Values:

Using the the DateSerial() function you can create a date object by providing the year, month and day as input. The following code creates a date object for the date April/5/2014 and prints it in cell A2:

Sub Example1()

Dim objDate As Date
'year, month, day
objDate = DateSerial(2014, 4, 5)

'prints the result in cell A1 
Cells(2, 1) = objDate
End Sub

CDate(), Creating (Converting) Date Objects From Strings:

Using the CDate function you can convert a string expression to a Date object. The code below converts the string expression “1/1/2013” to a Date object and prints the results in cell B2:

Sub Example2()

Dim objDate As Date
'A string expression
objDate = CDate("1/1/2013")

'prints the result in cell B2
Cells(2, 2) = objDate
End Sub

IsDate(), Checking if String is a Date Expression:

If the input argument to the CDate() function is not a date expression, you will get an exception. In order to check if a string is a valid date expression you can use the function IsDate(). The code below checks the two strings “Not a Date” and “3/2/2012”, and determines which one is a string expression, and prints the date in cell C2:

Sub Example3()
Dim objDate As Date
Dim strNotDate As String
Dim strDate As String

strNotDate = "Not a Date"
strDate = "3/2/2012"

If IsDate(strNotDate) = True Then
    'if its a valid date expression print the results in cell C2
    Cells(2, 3) = strNotDate
Else
    'if its not a date expression show a message box
    MsgBox ("The following string" + vbCr + """" + strNotDate _
    + """" + vbCr + "is not a valid date expression")
   
End If

If IsDate(strDate) = True Then
    Cells(2, 3) = strDate
Else
    MsgBox ("The following string" + vbCr + """" + strDate + """" _
    + vbCr + "is not a valid date expression")
End If

End Sub

Comparing Dates, Recent, Older …

Once you have created the date object you can compare them using the arithmetic operators <, =, > , <=, >= to see if they are the same  or which is more recent …  The following code takes two date expressions from the cells E2 and E3. Checks if they are valid date expressions, and prints the most recent one in cell E4:

Sub Example4()
Dim objDate1 As Date
Dim objDate2 As Date

If IsDate(Cells(2, 5)) = True Then
    objDate1 = CDate(Cells(2, 5))
Else
    MsgBox ("Invalid Input")
    Exit Sub
End If

If IsDate(Cells(3, 5)) = True Then
    objDate2 = CDate(Cells(3, 5))
Else
    MsgBox ("Invalid Input")
    Exit Sub
End If

'Note the smaller date is further in the past,
'there for the larger date would be recent
If objDate1 < objDate2 Then
    Cells(4, 5) = objDate2
Else
    Cells(4, 5) = objDate1
End If

End Sub

Getting The Year, Month and Day Values From A Date Object:

Using the functions Year(), Month(), Day() you can get the year month and day values of the date object. The following example takes the date expression in cell G2 and prints the year, month and day values in cells G3, G4 and G5 respectively:

Sub Example5()
Dim objDate As Date

If IsDate(Cells(2, 7)) = True Then
    objDate = CDate(Cells(2, 7))
Else
    MsgBox ("Invalid Input")
    Exit Sub
End If

'prints the year in cell G3
Cells(3, 7) = Year(objDate)
'prints the month in cell G4
Cells(4, 7) = Month(objDate)
'prints the day in cell G5
Cells(5, 7) = Day(objDate)

End Sub

Adding and Subtracting Years, Months and Days From Dates:

Using the DateSerial() function you can add years, months and days to a date object. The code below retrieves the date at cell F2, adds 3 years, 2 month and 5 days to it and prints the result in cell F3:

Sub Example6()
'the input date object
Dim objDate As Date
'the new date object
Dim objNewDate As Date
'the year value in the input date object
Dim intYear As Integer
'the month value in the input date object
Dim intMonth As Integer
'the day value in the input date object
Dim intDay As Integer

If IsDate(Cells(2, 9)) = True Then
    objDate = CDate(Cells(2, 9))
Else
    MsgBox ("Invalid Input")
    Exit Sub
End If

intYear = Year(objDate)
intMonth = Month(objDate)
intDay = Day(objDate)

'create the new date object with +3 year, +2 months and +5 days
objNewDate = DateSerial(intYear + 3, intMonth + 2, intDay + 5)

Cells(3, 9) = objNewDate

End Sub

Date(), Getting Current Date:

The function Date() returns the current date based on the computers calendar:

Sub Example7()
Dim objDate As Date

'gets the current date based on the computers calendar
objDate = Date
MsgBox (objDate)
End Sub

You can download the codes and files related to this article here.

If you need assistance with your code, or you are looking to hire a VBA programmer feel free to contact me. Also please visit my website  www.software-solutions-online.com

Понравилась статья? Поделить с друзьями:
  • Vba excel справка по русски
  • Vba excel список файлов в папке по маске
  • Vba excel список строк
  • Vba excel список списков
  • Vba excel список связей