Vba excel последний день месяца

 

NIKOLASCS

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

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

Какой функцией на VBA вернуть последний день месяца?

 

обязательно VBA?  
есть стандартная

 

The_Prist

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

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

Профессиональная разработка приложений для MS Office

Dim iLastDay As Integer  
iLastDay = Day(DateSerial(2010, 5, 1) — 1)  
iLastDay = Day(DateSerial(Year(Now), Month(Now), 1) — 1)

Даже самый простой вопрос можно превратить в огромную проблему. Достаточно не уметь формулировать вопросы…

 

NIKOLASCS

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

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

 
 

Владимир, читаем вопрос:  
{quote}{login=NIKOLASCS}{date=02.04.2010 07:19}{thema=Последний день месяца}{post}Какой функцией на VBA вернуть последний день месяца?{/post}{/quote}  
VBA нужно.

 
 

Юрий М

Модератор

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

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

Зачем тогда отвечаете? Формулы не просили.

 

vikttur

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

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

{quote}{login=Юрий М}{date=02.04.2010 02:00}{thema=}{post}Зачем тогда отвечаете? Формулы не просили.{/post}{/quote}  
Часто бывает, что спрашивающий не подозревает, что требуемое можно сделать без макросов, поэтому лищний пример не помешает. И вдруг потомкам… :)

 

Serge

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

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

{quote}{login=vikttur}{date=02.04.2010 05:20}{thema=Re: }{post}Часто бывает, что спрашивающий не подозревает, что требуемое можно сделать без макросов, поэтому лищний пример не помешает. И вдруг потомкам… :){/post}{/quote}  
Если потомкам, то надо пояснить, что КОНМЕСЯЦА появится только установки пакета анализа :-)

 

vikttur

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

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

У потомков она будет вшита. В подсознание :)

 

У нас каждый десятый только знает, чего хочет, вот и предлагаются возможные варианты…    
—  
Если подойдет функция, то и о пакете анализа расскажем.

 

Если при помощи предложенной функции вычислять последний день  
то получается что последний день мая 2012 года — 30!  
Как можно исправить эту функцию чтобы считать правильно?  
Dim iLastDay As Integer  
iLastDay = Day(DateSerial(2011, 5, 1) — 1)

 

egonomist

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

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

Узнаем последнее число следующего месяца  
1) x = Dateadd(«m»,1,Date) ‘- вспомогательная дата должна быть на один месяц больше интересующего нас месяца  
2) lastDate = Dateserial(Year(x), Month(x),0) ‘дата последнего числа интересущего месяца  
3) DayinMonth = Day(lastDate) ‘цифра-результат

 

egonomist

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

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

т.о для мая  
x = «01.06.2012»  
lastDate = Dateserial(Year(x), Month(x),0) ’31/05/2012  
DayinMonth = Day(lastDate) ’31

 

ДМ

Гость

#16

06.04.2012 11:24:50

Спасибо за быстрый ответ. Очень признателен.

You can use a user-defined function GetLastDayOfMonth() and pass the range you are interested in:

Option Explicit

Public Function GetLastDayOfMonth(ByVal myDate As Date) As Date
    GetLastDayOfMonth = DateSerial(Year(myDate), Month(myDate) + 1, 0)
End Function

Public Sub TestMe()

    Range("A1") = DateSerial(2000, 11, 11)
    If Range("A1") = GetLastDayOfMonth(Range("A1")) Then
        Debug.Print "LAST DAY!"
    End If

    Range("A1") = DateSerial(2000, 12, 31)
    If Range("A1") = GetLastDayOfMonth(Range("A1")) Then
        Debug.Print "LAST DAY! " & Range("A1")
        Range("A1") = DateAdd("d", 1, Range("A1"))
    End If

End Sub

The function checks the month and the year of the date, which is passed and it returns a new date, which is the last day of the month for this specific month and year.

Then in the TestMe version, you can compare a given date with the last day of the month, generated by the function. If the dates are the same, then this date is the last day of the corresponding month. Using DateAdd() it is possible to get the next day of the lastDay.

In the example above, I have explicitly written Range(«A1») 9 times, thus it is probably easier to follow.

Skip to content

Exceldome

Exceldome

This tutorial shows how to return the last day of a specific month using an Excel formula or VBA

Example: Return last day of a month

Return last day of a month

METHOD 1. Return last day of a month using Excel formula

EXCEL

This formula uses the Excel EOMONTH function to calculate the last day of a selected month. Using the month criteria of 0 means that the EOMONTH function will calculate the last day of the selected month.

METHOD 1. Return last day of a month using VBA

VBA

Sub Last_Days_of_a_Month()

‘declare a variable
Dim ws As Worksheet

Set ws = Worksheets(«Analysis»)

‘return the last day in a month
ws.Range(«D5») = Application.WorksheetFunction.EoMonth(ws.Range(«B5»), 0)

End Sub

ADJUSTABLE PARAMETERS
Output Range: Select the output range by changing the cell reference («D5») in the VBA code.
Month: Select the date that represents the month for which you want to get the last day of that month by changing the cell reference («B5»), in the VBA code, or enter the date with the relevant month in cell («B5»).
Worksheet Selection: Select the worksheet which captures the date that represents the month for which you want to get the last day of that month by changing the Analysis worksheet name in the VBA code. You can also change the name of this object variable, by changing the name ‘ws’ in the VBA code.

Explanation how to extract the last day of a month

EXPLANATION

EXPLANATION

This tutorial shows how to get the last day of a specific month through the use of an Excel formula or VBA.

Both the Excel formula and VBA methods make use of the EOMONTH function, with a month criteria of 0, to return the last day of a specific month.

FORMULA
=EOMONTH(date,0)

ARGUMENTS
date: The date that represents the month of which you want to return the last day.

Related Topic Description Related Topic and Description
Return number of days in a month How to return the number of days in a specific month using Excel and VBA
Return previous month based on current month How to return the previous month based on the current month using Excel and VBA
Return next month based on current month How to return the next month based on the current month using Excel and VBA

Date yes Add (Subtract) Days to a Date Concatenate Dates Convert Date to Number Convert Date to Text Month Name to Number Create Date Range from Dates Day Number of Year Month Name from Date First Day of Month Add (Subtract) Weeks to a Date If Functions with Dates Max Date Number of Days Between Dates Number of Days in a Month Number of Weeks Between Dates Number of Years Between Dates Split Date & Time into Separate Cells Countdown Remaining Days Insert Dates Random Date Generator Using Dynamic Ranges — Year to Date Values Add (Subtract) Years to a Date Date Formula Examples Extract Day from Date Get Day Name from Date Count Days Left in Month / Year Count Workdays Left in Month / Year Get Last Day of Month Last Business Day of Month / Year Number of Work / Business Days in Month Weekday Abbreviations Auto Populate Dates Number of Months Between Dates Quarter from a Date Years of Service Change Date Format Compare Dates Time yes Add (Subtract) Hours to Time Add (Subtract) Minutes to Time Add (Subtract) Seconds to Time Add Up time (Total Time) Time Differences Change Time Format Convert Minutes to Hours Convert Time to Decimal Convert Time to Hours Convert Time to Minutes Convert Time to Seconds Military Time Round Time to Nearest 15 Minutes Overtime Calculator Number of Hours Between Times Convert Seconds to Minutes, Hours, or Time Count Hours Worked Time Differences Time Format — Show Minutes Seconds Text yes Add Commas to Cells Get First Word from Text Capitalize First Letter Clean & Format Phone #s Remove Extra Trailing / Leading Spaces Add Spaces to Cell Assign Number Value to Text Combine Cells with Comma Combine First and Last Names Convert Text String to Date Convert Text to Number Extract Text From Cell Get Last Word Remove Unwated Characters Extract Text Before or After Character How to Split Text String by Space, Comma, & More Remove Special Characters Remove First Characters from Left Substitute Multiple Values Switch First & Last Names w/ Commas Remove Specific Text from a Cell Extract Text Between Characters (Ex. Parenthesis) Add Leading Zeros to a Number Remove Line Breaks from Text Remove all Numbers from Text Reverse Text Remove Non-Numeric Characters Remove Last Character(s) From Right Separate First and Last Names Separate Text & Numbers Round yes Round Formulas Round Price to Nearest Dollar or Cent Round to Nearest 10, 100, or 1000 Round to Nearest 5 or .5 Round Percentages Round to Significant Figures Count yes Count Blank and Non-blank Cells Count Cells Between Two Numbers Count Cells not Equal to Count if Cells are in Range Count Times Word Appears in Cell Count Words in Cell Count Specific Characters in Column Count Total Number of Characters in Column Count Cells that Equal one of two Results Count Cells that do not Contain Count Cells that Contain Specific Text Count Unique Values in Range Countif — Multiple Criteria Count Total Number of Cells in Range Count Cells with Any Text Count Total Cells in a Table Lookup yes Two Dimensional VLOOKUP VLOOKUP Simple Example Vlookup — Multiple Matches Case Sensitive Lookup Case Sensitive VLOOKUP Sum if — VLOOKUP Case Sensitive Lookup Case Sensitive VLOOKUP Find Duplicates w/ VLOOKUP or MATCH INDEX MATCH MATCH Lookup — Return Cell Address (Not Value) Lookup Last Value in Column or Row Reverse VLOOKUP (Right to Left) Risk Score Bucket with VLOOKUP Sum with a VLOOKUP Function VLOOKUP & INDIRECT VLOOKUP Concatenate VLOOKUP Contains (Partial Match) 17 Reasons Why Your XLOOKUP is Not Working Double (Nested) XLOOKUP — Dynamic Columns IFERROR (& IFNA) XLOOKUP Lookup Min / Max Value Nested VLOOKUP Top 11 Alternatives to VLOOKUP (Updated 2022!) VLOOKUP – Dynamic Column Reference VLOOKUP – Fix #N/A Error VLOOKUP – Multiple Sheets at Once VLOOKUP & HLOOKUP Combined VLOOKUP & MATCH Combined VLOOKUP Between Worksheets or Spreadsheets VLOOKUP Duplicate Values VLOOKUP Letter Grades VLOOKUP Return Multiple Columns VLOOKUP Returns 0? Return Blank Instead VLOOKUP w/o #N/A Error XLOOKUP Multiple Sheets at Once XLOOKUP Between Worksheets or Spreadsheets XLOOKUP by Date XLOOKUP Duplicate Values XLOOKUP Multiple Criteria XLOOKUP Return Multiple Columns XLOOKUP Returns 0? Return Blank Instead XLOOKUP Text XLOOKUP with IF XLOOKUP With If Statement Misc. yes Sort Multiple Columns Use Cell Value in Formula Percentage Change Between Numbers Percentage Breakdown Rank Values Add Spaces to Cell CAGR Formula Average Time Decimal Part of Number Integer Part of a Number Compare Items in a List Dealing with NA() Errors Get Worksheet Name Wildcard Characters Hyperlink to Current Folder Compound Interest Formula Percentage Increase Create Random Groups Sort with the Small and Large Functions Non-volatile Function Alternatives Decrease a Number by a Percentage Calculate Percent Variance Profit Margin Calculator Convert Column Number to Letter Get Full Address of Named Range Insert File Name Insert Path Latitute / Longitude Functions Replace Negative Values Reverse List Range Convert State Name to Abbreviation Create Dynamic Hyperlinks Custom Sort List with Formula Data Validation — Custom Formulas Dynamic Sheet Reference (INDIRECT) Reference Cell in Another Sheet or Workbook Get Cell Value by Address Get Worksheet Name Increment Cell Reference List Sheet Names List Skipped Numbers in Sequence Return Address of Max Value in Range Search by Keywords Select Every Other (or Every nth) Row Basics yes Cell Reference Basics — A1, R1C1, 3d, etc. Add Up (Sum) Entire Column or Row Into to Dynamic Array Formulas Conversions yes Convert Time Zones Convert Celsius to Fahrenheit Convert Pounds to Kilograms Convert Time to Unix Time Convert Feet to Meters Convert Centimeters to Inches Convert Kilometers to Miles Convert Inches to Feet Convert Date to Julian Format Convert Column Letter to Number Tests yes Test if a Range Contains any Text Test if any Cell in Range is Number Test if a Cell Contains a Specific Value Test if Cell Contains Any Number Test if Cell Contains Specific Number Test if Cell is Number or Text If yes Percentile If Subtotal If Sumproduct If Large If and Small If Median If Concatentate If Max If Rank If TEXTJOIN If Sum yes Sum if — Begins With / Ends With Sum if — Month or Year to Date Sum if — By Year Sum if — Blank / Non-Blank Sum if — Horizontal Sum Count / Sum If — Cell Color INDIRECT Sum Sum If — Across Multiple Sheets Sum If — By Month Sum If — Cells Not Equal To Sum If — Not Blank Sum if — Between Values Sum If — Week Number Sum Text Sum if — By Category or Group Sum if — Cell Contains Specific Text (Wildcards) Sum if — Date Rnage Sum if — Dates Equal Sum if — Day of Week Sum if — Greater Than Sum if — Less Than Average yes Average Non-Zero Values Average If — Not Blank Average — Ignore 0 Average — Ignore Errors Math yes Multiplication Table Cube Roots nth Roots Square Numbers Square Roots Calculations yes Calculate a Ratio Calculate Age KILLLLLLL Calculate Loan Payments GPA Formula Calculate VAT Tax How to Grade Formulas Find yes Find a Number in a Column / Workbook Find Most Frequent Numbers Find Smallest n Values Find nth Occurance of Character in Text Find and Extract Number from String Find Earliest or Latest Date Based on Criteria Find First Cell with Any Value Find Last Row Find Last Row with Data Find Missing Values Find Largest n Values Most Frequent Number Conditional Formatting yes Conditional Format — Dates & Times Conditional Format — Highlight Blank Cells New Functions XLOOKUP Replaces VLOOKUP, HLOOKUP, and INDEX / MATCH Logical yes AND Checks whether all conditions are met. TRUE/FALSE IF If condition is met, do something, if not, do something else. IFERROR If result is an error then do something else. NOT Changes TRUE to FALSE and FALSE to TRUE. OR Checks whether any conditions are met. TRUE/FALSE XOR Checks whether one and only one condition is met. TRUE/FALSE Lookup & Reference yes FALSE The logical value: FALSE. TRUE The logical value: TRUE. ADDRESS Returns a cell address as text. AREAS Returns the number of areas in a reference. CHOOSE Chooses a value from a list based on it’s position number. COLUMN Returns the column number of a cell reference. COLUMNS Returns the number of columns in an array. HLOOKUP Lookup a value in the first row and return a value. HYPERLINK Creates a clickable link. INDEX Returns a value based on it’s column and row numbers. INDIRECT Creates a cell reference from text. LOOKUP Looks up values either horizontally or vertically. MATCH Searches for a value in a list and returns its position. OFFSET Creates a reference offset from a starting point. ROW Returns the row number of a cell reference. ROWS Returns the number of rows in an array. TRANSPOSE Flips the oriention of a range of cells. VLOOKUP Lookup a value in the first column and return a value. Date & Time yes DATE Returns a date from year, month, and day. DATEDIF Number of days, months or years between two dates. DATEVALUE Converts a date stored as text into a valid date DAY Returns the day as a number (1-31). DAYS Returns the number of days between two dates. DAYS360 Returns days between 2 dates in a 360 day year. EDATE Returns a date, n months away from a start date. EOMONTH Returns the last day of the month, n months away date. HOUR Returns the hour as a number (0-23). MINUTE Returns the minute as a number (0-59). MONTH Returns the month as a number (1-12). NETWORKDAYS Number of working days between 2 dates. NETWORKDAYS.INTL Working days between 2 dates, custom weekends. NOW Returns the current date and time. SECOND Returns the second as a number (0-59) TIME Returns the time from a hour, minute, and second. TIMEVALUE Converts a time stored as text into a valid time. TODAY Returns the current date. WEEKDAY Returns the day of the week as a number (1-7). WEEKNUM Returns the week number in a year (1-52). WORKDAY The date n working days from a date. WORKDAY.INTL The date n working days from a date, custom weekends. YEAR Returns the year. YEARFRAC Returns the fraction of a year between 2 dates. Engineering yes CONVERT Convert number from one unit to another. Financial yes FV Calculates the future value. PV Calculates the present value. NPER Calculates the total number of payment periods. PMT Calculates the payment amount. RATE Calculates the interest Rate. NPV Calculates the net present value. IRR The internal rate of return for a set of periodic CFs. XIRR The internal rate of return for a set of non-periodic CFs. PRICE Calculates the price of a bond. YIELD Calculates the bond yield. INTRATE The interest rate of a fully invested security. Information yes CELL Returns information about a cell. ERROR.TYPE Returns a value representing the cell error. ISBLANK Test if cell is blank. TRUE/FALSE ISERR Test if cell value is an error, ignores #N/A. TRUE/FALSE ISERROR Test if cell value is an error. TRUE/FALSE ISEVEN Test if cell value is even. TRUE/FALSE ISFORMULA Test if cell is a formula. TRUE/FALSE ISLOGICAL Test if cell is logical (TRUE or FALSE). TRUE/FALSE ISNA Test if cell value is #N/A. TRUE/FALSE ISNONTEXT Test if cell is not text (blank cells are not text). TRUE/FALSE ISNUMBER Test if cell is a number. TRUE/FALSE ISODD Test if cell value is odd. TRUE/FALSE ISREF Test if cell value is a reference. TRUE/FALSE ISTEXT Test if cell is text. TRUE/FALSE N Converts a value to a number. NA Returns the error: #N/A. TYPE Returns the type of value in a cell. Math yes ABS Calculates the absolute value of a number. AGGREGATE Define and perform calculations for a database or a list. CEILING Rounds a number up, to the nearest specified multiple. COS Returns the cosine of an angle. DEGREES Converts radians to degrees. DSUM Sums database records that meet certain criteria. EVEN Rounds to the nearest even integer. EXP Calculates the exponential value for a given number. FACT Returns the factorial. FLOOR Rounds a number down, to the nearest specified multiple. GCD Returns the greatest common divisor. INT Rounds a number down to the nearest integer. LCM Returns the least common multiple. LN Returns the natural logarithm of a number. LOG Returns the logarithm of a number to a specified base. LOG10 Returns the base-10 logarithm of a number. MOD Returns the remainder after dividing. MROUND Rounds a number to a specified multiple. ODD Rounds to the nearest odd integer. PI The value of PI. POWER Calculates a number raised to a power. PRODUCT Multiplies an array of numbers. QUOTIENT Returns the integer result of division. RADIANS Converts an angle into radians. RAND Calculates a random number between 0 and 1. RANDBETWEEN Calculates a random number between two numbers. ROUND Rounds a number to a specified number of digits. ROUNDDOWN Rounds a number down (towards zero). ROUNDUP Rounds a number up (away from zero). SIGN Returns the sign of a number. SIN Returns the sine of an angle. SQRT Calculates the square root of a number. SUBTOTAL Returns a summary statistic for a series of data. SUM Adds numbers together. SUMIF Sums numbers that meet a criteria. SUMIFS Sums numbers that meet multiple criteria. SUMPRODUCT Multiplies arrays of numbers and sums the resultant array. TAN Returns the tangent of an angle. TRUNC Truncates a number to a specific number of digits. Stats yes AVERAGE Averages numbers. AVERAGEA Averages numbers. Includes text & FALSE =0, TRUE =1. AVERAGEIF Averages numbers that meet a criteria. AVERAGEIFS Averages numbers that meet multiple criteria. CORREL Calculates the correlation of two series. COUNT Counts cells that contain a number. COUNTA Count cells that are non-blank. COUNTBLANK Counts cells that are blank. COUNTIF Counts cells that meet a criteria. COUNTIFS Counts cells that meet multiple criteria. FORECAST Predict future y-values from linear trend line. FREQUENCY Counts values that fall within specified ranges. GROWTH Calculates Y values based on exponential growth. INTERCEPT Calculates the Y intercept for a best-fit line. LARGE Returns the kth largest value. LINEST Returns statistics about a trendline. MAX Returns the largest number. MEDIAN Returns the median number. MIN Returns the smallest number. MODE Returns the most common number. PERCENTILE Returns the kth percentile. PERCENTILE.INC Returns the kth percentile. Where k is inclusive. PERCENTILE.EXC Returns the kth percentile. Where k is exclusive. QUARTILE Returns the specified quartile value. QUARTILE.INC Returns the specified quartile value. Inclusive. QUARTILE.EXC Returns the specified quartile value. Exclusive. RANK Rank of a number within a series. RANK.AVG Rank of a number within a series. Averages. RANK.EQ Rank of a number within a series. Top Rank. SLOPE Calculates the slope from linear regression. SMALL Returns the kth smallest value. STDEV Calculates the standard deviation. STDEV.P Calculates the SD of an entire population. STDEV.S Calculates the SD of a sample. STDEVP Calculates the SD of an entire population TREND Calculates Y values based on a trendline. Text yes CHAR Returns a character specified by a code. CLEAN Removes all non-printable characters. CODE Returns the numeric code for a character. CONCATENATE Combines text together. DOLLAR Converts a number to text in currency format. EXACT Test if cells are exactly equal. Case-sensitive. TRUE/FALSE FIND Locates position of text within a cell.Case-sensitive. LEFT Truncates text a number of characters from the left. LEN Counts number of characters in text. LOWER Converts text to lower case. MID Extracts text from the middle of a cell. PROPER Converts text to proper case. REPLACE Replaces text based on it’s location. REPT Repeats text a number of times. RIGHT Truncates text a number of characters from the right. SEARCH Locates position of text within a cell.Not Case-sensitive. SUBSTITUTE Finds and replaces text. Case-sensitive. TEXT Converts a value into text with a specific number format. TRIM Removes all extra spaces from text. UPPER Converts text to upper case. VALUE Converts a number stored as text into a number.

Sometimes we need to get an end-of-month date to use as a completion date, a due date, as a target date, or sometimes we need it to calculate the days between two dates.

Without any effort, we can easily add it manually, but there are some formulas that can help us to calculate it.

The best way to calculate the last date of the month is by using the EOMONTH Function. But apart from this, you can also use other methods (VBA).

Using a formula or any other dynamic method has the benefit that we don’t need to calculate it again and again. Today, in this post, I’d like to share with you 3 simple and dynamic ways to get the end of the month date in Excel.

So let’s get started and please download this same file from here to follow along.

Get the Last Day of the Month using EOMONTH Function

EOMONTH is my favorite function to calculate the last day of a month. This function is specifically designed for these kinds of calculations.

All you have to do is just specify a date current date, and the number of months you want to calculate the last date before and after the start date. Here is the syntax:

EOMONTH(start_date,months)

In this syntax, the start date will be the current date and months will be a number that represents the number of months forward or backward.

Let’s say, you have the date “06-Feb-2017” and you want to get the last day of “Feb”. In this case, the formulas you need to use are:

=EOMONTH("22-Feb-2017",0)
get end of day for a present month using eomonth

In the above example, when you use EOMONTH, has returned 28-Feb-2017 which is the last date of the Feb month.

How does it work: Here, you have used “0” for the number argument because the start date you have used is of Feb month and you won’t have the last day of the same month. When you use “0” it will simply return the last date for the same month for which you have the start date.

To create a dynamic formula you can use the TODAY Function in the start_date argument.

End Date of the Future Month

Now, let’s say, from the same date you want to get the last day of “Apr”. In this case, the formulas you need to use are:

=EOMONTH("22-Feb-2017",2)
get end of the month date for future month using eomonth

In the above example, the formula has returned 30-Apr-2017 which is the last date of the Apr month.

How does it work

Here, you have used “2” for the number argument and the start date you have used is of Feb month. Now, if you look, Apr is exactly 2 months after Feb so that’s why it has returned 30-Apr-2017.

End Date of the Previous Month

And, if you want to get the last date of a previous month you can use a negative number for that. Let’s say you want the last day of Jan. So, the formula you need to use:

=EOMONTH("22-Feb-2017",-1)
get end of the month date for previous month using eomonth

In the above example, the formula has returned 31-Jan-2017 which is the last date of the Jan month.

How does it work: Here, you have used “-1” for the number argument and Jan is exactly 1 month before Feb.

DATE Function to Get Month’s Last Date

DATE Function is another approach to getting the last day in excel. The date function helps you to create a valid excel date by specifying the year, month, and day. Here is the syntax:

DATE(year,month,day)

As I have mentioned, in the date function, you need to enter the year, month, and day, and it returns a valid date according to that. Now, there is a small trick that you can do with day argument.

Quick Trick: If you use 0 asa day it will return the last date of the previous month. For example, if you specify, Year: 2017, Month: 4 (that’s May) and Day: 0 it will return 30-Apr-2017 in the result.

And, if you want to calculate the last day of the current month the formula will be:

get end of the month date using date function
=DATE(CurrentYear,CurrentMonth + 1,0)

Or, if you just have a date to refer then the formula will be:

=DATE(YEAR(date),MONTH(date)+1,0)

Get Last Day with a UDF

A great VBA Example. This is a macro code for using a VBA UDF to get the last day of the month. You just need to copy it into your VBA editor.

Function LastD(Optional sd As Date = 0) As Date
If sd = 0 Then 
sd = VBA.DateLastD = VBA.DateSerial(VBA.Year(sd), VBA.Month(sd) + 1, 0)
End Function
get end of the month date using vba

In your worksheet, type “=LastD(” and insert the date for the month or refer to a cell. And, if you want the last day of the current month then simply left it blank using brackets.

Conclusion

As I said, the month’s last day can be helpful for you while calculating target dates, due dates, or completion dates. And, now we have three different ways to get it.

If you use EOMONTH then it’s really easy to create a dynamic formula that can help you to date for past or future months and I think it’s the best way to do it.

I hope you found it useful and it will help you take your skills to the whole next level.

Now tell me one thing. Which one is your favorite method above all? Or, do you have a different method? Please share with me in the comment box, I would love to hear from you.

And, don’t forget to share it with your friends.

Хитрости »

23 Октябрь 2017              10913 просмотров


Проблема получения последнего дня месяца довольно распространена и очень просто решается. Начиная с Excel 2007 можно без всяких доп.манипуляций использовать функцию КОНМЕСЯЦА(EOMONTH):
=КОНМЕСЯЦА(ТДАТА();0)
=EOMONTH(NOW(),0)
ТДАТА(NOW) — возвращает текущую дату. Вместо неё можно указать любую дату и последняя дата месяца будет возвращена для указанной даты.
Для версий 2003 и ранее для использования КОНМЕСЯЦА(EOMONTH) необходимо для начала подключить надстройку Пакет анализа или же использовать чуть менее понятную формулу:
=ДАТА(ГОД(ТДАТА());МЕСЯЦ(ТДАТА())+1;0)
=DATE(YEAR(NOW()),MONTH(NOW())+1,0)
На самом деле данная формула проста, если разобраться детальнее. Функция ДАТА записывает в ячейку дату, на основании указанного года, месяца и дня. Мы для года берем год от текущей даты, далее берем месяц текущей даты и к месяцу прибавляем 1, чтобы получить следующий месяц. А потом для дня указываем 0, что заставляет Excel сдвинуть первую дату следующего месяца на один день назад. Таким образом и получается последняя дата месяца. Пошагово это выглядит так(если считать, что сегодня «22.10.2017»):
=ДАТА(ГОД(ТДАТА());МЕСЯЦ(ТДАТА())+1;0) =>
=ДАТА(ГОД(«22.10.2017»);МЕСЯЦ(«22.10.2017»)+1;0) =>
=ДАТА(2017;10+1;0) =>
=ДАТА(2017;11;0) здесь уже получится 01.11.2017, но 0 в качестве дня заставляет вернуться на день назад =>
=31.10.2017


Но есть более сложная проблема — получить дату последнего рабочего дня месяца. А это уже не так просто. Встроенных функций(вроде КОНМЕСЯЦА) для этого в Excel нет. А это значит опять придется танцевать с бубном.
Сразу возникает вопрос: а зачем это вообще может потребоваться? Например, для поиска счетов, отгрузка по которым производилась в последний рабочий день месяца, а оплаты(или документы на отгрузку) по некоторым пришли только в начале следующего. Так же такую функцию будет удобно применять для автоматического формирования платежек или накладных, если они должны быть оформлены именно последним рабочим днем месяца.
Чтобы получить именно корректную дату следует так же учесть и тот факт, что есть дни праздничные. И их тоже надо как-то учесть. Для этого я буду использовать отдельный лист Праздники, в столбце А которого записаны праздничные дни на пару лет. Также в этом диапазоне перечислены и все выходные. Сделано для более корректного подсчета дат, т.к. праздники могут быть перенесены, в результате чего рабочими становятся субботы или воскресенья. Если их не учитывать, то расчет будет неверным.

Из спортивного интереса создать такую функцию решил тремя способами:

  • При помощи стандартных функций Excel
  • При помощи функции пользователя на VBA
  • При помощи PowerQuery

Последний рабочий день при помощи стандартных функций Excel
В ходе некоторых экспериментов и манипуляций появилась такая формула:
=РАБДЕНЬ(
ЕСЛИ(ДЕНЬНЕД(КОНМЕСЯЦА(B4;0);2)<6; КОНМЕСЯЦА(B4;0);
КОНМЕСЯЦА(B4;0)-(ДЕНЬНЕД(КОНМЕСЯЦА(B4;0);2)-5));
0; Праздники!$A$2:$A$827)
=WORKDAY(
IF(WEEKDAY(EOMONTH(B4,0),2)<6, EOMONTH(B4,0),
EOMONTH(B4,0)-(WEEKDAY(EOMONTH(B4,0),2)-5)),
0,Праздники!$A$2:$A$827)
где Праздники!$A$2:$A$827 — ссылка на диапазон дат с праздниками
Здесь я так же использую КОНМЕСЯЦА для быстрого определения последней даты месяца.
Функция ДЕНЬНЕД(WEEKDAY) возвращает номер дня недели для указанной даты и нужна для того, чтобы определить — является последний день недели субботой или воскресеньем. Если нет, то возвращаем дату как есть, если это суббота или воскресенье — то отнимаем от даты либо 1 день, либо 2(если это СБ — то 1, если ВСК — то 2).
И только после этого применяем к полученной дате функцию РАБДЕНЬ(WORKDAY), которая для последней даты месяца определяет, является ли она праздничной(на основании списка праздников Праздники!$A$2:$A$827). Если дата праздничная — то она уменьшается до тех пор, пока не достигнет рабочего дня. РАБДЕНЬ не принимает в расчет выходные, поэтому нам и нужны функции ЕСЛИ и ДЕНЬНЕД, прежде чем применить РАБДЕНЬ.

Однако сразу хочу оговорить, что в конкретно моем случае вычисление выходных дней при помощи ЕСЛИ и ДЕНЬНЕД несколько избыточно, т.к. в диапазоне с праздниками помимо непосредственно праздников у меня уже учтены все выходные дни. Т.е. по сути формула могла бы быть намного проще:
=РАБДЕНЬ(КОНМЕСЯЦА(B4;0); 0; Праздники!$A$2:$A$827)
=WORKDAY(EOMONTH(B4,0), 0, Праздники!$A$2:$A$827)
Но я все равно решил именно в статье привести формулу, которая смотрит и на дни недели, т.к. требования могут быть разными.

Т.к. Microsoft все же немного заботится о нас, то для пользователей версий Excel 2010 и более новых, в случае необходимости учитывать день недели прямо в формуле, можно использовать функцию РАБДЕНЬ.МЕЖД:
=РАБДЕНЬ.МЕЖД(КОНМЕСЯЦА(B4;0);0;1;Праздники!$A$2:$A$827)
=WORKDAY.INTL(EOMONTH(B4,0),0,1,Праздники!$A$2:$A$827)
РАБДЕНЬ.МЕЖД[дата; кол-во дней; выходные; праздники]
дата — дата, от которой необходимо отсчитать указанное кол-во дней
кол-во дней — количество дней, которые надо прибавить или отнять(отриц. число — отнимает дни от даты) от указанной даты
выходные — 1 = Суббота и Воскресенье, 2 — Воскресенье и Понедельник и т.д. Полный перечень есть в справке для функции и в выпадающей подсказке к функции при вводе.
праздники — ссылка на диапазон дат с праздниками
Достаточно указать последнюю дату месяца, указать для неё сдвиг на 0 дней, указать тип выходных и ссылку на диапазон дат с праздниками. Все уже сделано и все гораздо проще.


Последний рабочий день при помощи функции пользователя на VBA

Если использование VBA не является для вас проблемой, то можно применить функцию пользователя(UDF) для расчета последнего рабочего дня:

'---------------------------------------------------------------------------------------
' Author : The_Prist(Щербаков Дмитрий)
'          Профессиональная разработка приложений для MS Office любой сложности
'          Проведение тренингов по MS Excel
'          http://www.excel-vba.ru
'          WebMoney - R298726502453; Яндекс.Деньги - 41001332272872
' Purpose: Функция получения последнего рабочего дня на основании указанной даты и списка праздников
'---------------------------------------------------------------------------------------
Option Explicit
 
Function ПоследнийРабочийДень(Дата As Date, Optional Праздники As Range = Nothing, Optional СистемныеВыходные As Boolean = False)
    Dim dd As Date, dres As Date
    Dim lWeekDay As Long
 
    dres = DateSerial(Year(Дата), Month(Дата) + 1, 0)
    If СистемныеВыходные Then
        lWeekDay = Weekday(dres, vbUseSystemDayOfWeek)
        If lWeekDay < 6 Then
            dres = dres
        Else
            dres = dres - (lWeekDay - 5)
        End If
    End If
    Do While (IsHoliday(dres, Праздники))
        dres = dres - 1
    Loop
    ПоследнийРабочийДень = dres
End Function
 
'Функция поиска указанной даты среди праздничных дат
'       dd          - искомая дата
'       Holidays    - диапазон с праздничными днями
Function IsHoliday(ByVal dd As Date, Optional Holidays As Range = Nothing)
    Dim lWeekDay As Long
    Dim x, rr As Range
 
    If Holidays Is Nothing Then Exit Function
    For Each x In Holidays.Value
        If IsDate(x) Then
            If CDate(x) = dd Then
                IsHoliday = True
                Exit Function
            End If
        End If
    Next
End Function

Чтобы правильно использовать приведенный код, необходимо сначала ознакомиться со статьей Что такое функция пользователя(UDF)?. Вкратце: скопировать текст кода выше, перейти в редактор VBA(Alt+F11) -создать стандартный модуль(InsertModule) и в него вставить скопированный текст. После чего функцию можно будет вызвать из Диспетчера функций(Ctrl+F3), отыскав её в категории Определенные пользователем (User Defined Functions).
Синтаксис функции:
=ПоследнийРабочийДень(B4;Праздники!$A$2:$A$827;0)

  • Дата(B4) — непосредственно дата или ссылка на ячейку с датой, последней рабочий день для которой необходимо вычислить. Будет рассчитан последний рабочий день для месяца указанной даты.
  • Праздники() — ссылка на диапазон ячеек, содержащих даты праздничных дней.
  • СистемныеВыходные(0) — ИСТИНА(TRUE или 1) или ЛОЖЬ(FALSE или 0). Если указано как ЛОЖЬ, то при вычислении последнего рабочего дня не будут учитываться выходные. В этом случае они обязательно должны быть перечислены в списке Праздники. Если они не перечислены — то все дни недели считаются рабочими, кроме праздников. Если указано как ИСТИНА, то в качестве выходных будут применены те дни, которые установлены для календаря в операционной системе. Для русской локализации это как правило Суббота и Воскресенье.

Последний рабочий день при помощи PowerQuery

Самый экзотический метод. Если еще не знаете что такое PowerQuery — Power Query — что такое и почему её необходимо использовать в работе?.
Для начала необходимо загрузить список праздников.

Если список праздников еще не преобразован в умную таблицу, то на листе Праздники выделяем все ячейки с датами -переходим на вкладку Вставка(Insert)Таблица(Table). Снимаем галку с пункта «Таблица с заголовками» —Ок:
Создание умной таблицы

Выделяем любую ячейку в созданной таблице праздников -переходим на вкладку Данные(Data или Power Query) и выбираем Из таблицы(From Table).
Нажимаем в заголовке на значок календаря и в выпадающем списке выбираем тип Дата:
Изменить тип на Дата
В правой части окна редактора изменяем название запроса(скорее всего там Таблица1) на Праздники:
Переименование запроса
Переходим на вкладку Главная, раскрываем пункт Закрыть и загрузить и выбираем Закрыть и загрузить в…:
Загрузить
В появившемся окне выбираем Только создать подключение и нажимаем Ок:
Создать подключение
Теперь переходим на вкладку Данные(Data) -Получить данные -Из других источников -Пустой запрос. Переходим в расширенный редактор(вкладка ГлавнаяРасширенный редактор):
Расширенный редактор
и вставляем туда следующий текст:

let
dNow = Date.From(DateTime.LocalNow()),
//dNow = Date.FromText(«2017-09-19»),
lastDay = Date.EndOfMonth(dNow),
WeekD = Date.DayOfWeek(lastDay,1),
dd = if WeekD < 5 then lastDay else Date.AddDays(lastDay,-(WeekD-4)),
//dd = dNow,
coun_dif = (value as date) as date =>
let
dAdd = value,
select_rows = Table.SelectRows(Праздники, each Record.Field(_, «Дата выходного дня») = dAdd),
count_rows = Table.RowCount(select_rows),
result = Date.AddDays(value,-count_rows)
in
result,
res_d = Table.FromValue(coun_dif(dd))
in
res_d

После этого можно на вкладке Главная нажать Закрыть и загрузить. Будет создан новый лист с одной ячейкой — датой последнего рабочего дня.
Чтобы приведенный запрос работал корректно, необходимо назвать столбец с праздничными датами «Дата выходного дня». Либо изменить это название в самом запросе.
Если нужен последний рабочий день на конкретную дату, то необходимо убрать первую строку(dNow = Date.From(DateTime.LocalNow()),) и убрать слеши вначале следующей строки:
let
dNow = Date.FromText(«2017-09-19»),
lastDay = Date.EndOfMonth(dNow),
WeekD = Date.DayOfWeek(lastDay,1),
dd = if WeekD < 5 then lastDay else Date.AddDays(lastDay,-(WeekD-4)),
//dd = Date.EndOfMonth(dNow),
coun_dif = (value as date) as date =>
let
dAdd = value,
select_rows = Table.SelectRows(Праздники, each Record.Field(_, «Дата выходного дня») = dAdd),
count_rows = Table.RowCount(select_rows),
result = Date.AddDays(value,-count_rows)
in
result,
res_d = Table.FromValue(coun_dif(dd))
in
res_d
Если выходные не надо учитывать(чтобы суббота и воскресенье не рассчитывались автоматом в зависимости от дня недели), то запрос будет выглядеть так:
let
dNow = Date.FromText(«2017-09-19»),
dd = Date.EndOfMonth(dNow),
coun_dif = (value as date) as date =>
let
dAdd = value,
select_rows = Table.SelectRows(Праздники, each Record.Field(_, «Дата выходного дня») = dAdd),
count_rows = Table.RowCount(select_rows),
result = Date.AddDays(value,-count_rows)
in
result,
res_d = Table.FromValue(coun_dif(dd))
in
res_d

Реализацию всех приведенных решений можно скачать в приложенном файле
Скачать файл:

  ПоследнийРабочийДень.xlsm (50,7 KiB, 617 скачиваний)


Статья помогла? Поделись ссылкой с друзьями!

  Плейлист   Видеоуроки


Поиск по меткам



Access
apple watch
Multex
Power Query и Power BI
VBA управление кодами
Бесплатные надстройки
Дата и время
Записки
ИП
Надстройки
Печать
Политика Конфиденциальности
Почта
Программы
Работа с приложениями
Разработка приложений
Росстат
Тренинги и вебинары
Финансовые
Форматирование
Функции Excel
акции MulTEx
ссылки
статистика

Artur zhitkovic

15 / 2 / 1

Регистрация: 24.10.2014

Сообщений: 106

1

Определить последний день текущего месяца

10.12.2016, 19:17. Показов 11009. Ответов 1

Метки нет (Все метки)


Студворк — интернет-сервис помощи студентам

Есть задание : Определить, сколько часов и минут осталось до конца текущего месяца.
Вот что я сделал, но как задать последний день месяца на автомате

Visual Basic
1
2
3
4
5
6
Public Sub zad2()
Dim h As Long, m As Long
m = DateDiff("n", Now, "31/12/2016")
h = m / 60
MsgBox "До конца месяца, осталось " & h & " ч " & m Mod 60 & " мин"
End Sub

Сам нашел
Если кому надо

Visual Basic
1
LastDayInMoth =  DateSerial(Year(Now), Month(Now) + 1, 0)



0



15136 / 6410 / 1730

Регистрация: 24.09.2011

Сообщений: 9,999

10.12.2016, 20:11

2

Artur zhitkovic, h = m 60 (иначе будет округление, а не отбрасывание дробной части)

Цитата
Сообщение от Artur zhitkovic
Посмотреть сообщение

Сам нашел



0



IT_Exp

Эксперт

87844 / 49110 / 22898

Регистрация: 17.06.2006

Сообщений: 92,604

10.12.2016, 20:11

Помогаю со студенческими работами здесь

Определить номер последней недели текущего месяца
Ребята, нужно найти последнюю неделю текущего месяца. и если сейчас она, то :
к…

Определить дату, название месяца, квартал, неделю года, день недели
Для заданной даты и определенного значения определить дату, название месяца, квартал, неделю года,…

Как определить первый и последний день текущего месяца?
Подскажите пожалуйста, как определить первый и последний день текущего месяца?

declare…

Как найти последний день текущего месяца?
Здравствуйте!

Есть кнопка, при нажатии на которую в полях дат должны устанавливаться первое и…

Искать еще темы с ответами

Или воспользуйтесь поиском по форуму:

2

Содержание

  • EOMONTH Обзор функций
  • EOMONTH Синтаксис и входные данные функции:
  • Как использовать функцию EOMONTH
  • Последний день месяца
  • Количество дней в месяце
  • Первый день месяца
  • EOMONTH в Google Таблицах
  • EOMONTH Примеры в VBA

Скачать пример рабочей книги

Загрузите образец книги

В этом руководстве показано, как использовать Функция Excel EOMONTH в Excel, чтобы найти последний день месяца через n месяцев.

Функция EOMONTH Возвращает последний день месяца за n месяцев от даты начала.

Чтобы использовать функцию листа Excel EOMONTH, выберите ячейку и введите:

(Обратите внимание, как появляется ввод формулы)

EOMONTH Синтаксис и входные данные функции:

1 = EOMONTH (начальная_дата, месяцы)

Дата начала — Дата начала в формате серийного номера Excel или введенная как дата с цитатами вокруг даты. Пример: нельзя вводить 11.12.2015 прямо в ячейку. Вместо этого вам нужно ввести «11/12/2015», или вам нужно будет использовать соответствующий серийный номер: 42320. В качестве альтернативы вы можете указать ячейку с введенной датой 11/12/2015. Excel автоматически преобразует даты, хранящиеся в ячейках, в последовательный формат (если дата не вводится как текст).

месяцы — Количество месяцев до даты начала. Число может быть положительным (будущее) или отрицательным (прошлое).

Как использовать функцию EOMONTH

Последний день месяца

Текущий месяц

Функция EOMONTH принимает дату и возвращает последний день месяца:

Предыдущий месяц

Вы также можете добавить (или вычесть) n месяцев к дате начала, чтобы получить последний день другого месяца. Этот пример вернет последний день предыдущего месяца:

Количество дней в месяце

Используя функцию ДЕНЬ, вы можете рассчитать количество дней в месяце:

1 = ДЕНЬ (EOMONTH (B3,0))

Функция ДЕНЬ возвращает номер дня в дате. Используя EOMONTH, мы можем получить последний день месяца, а функция DAY затем возвращает соответствующий номер дня.

Первый день месяца

Добавив 1 к результату функции EOMONTH, вы можете получить первый день месяца:

Примечание: в Excel даты хранятся как порядковые номера, где каждое число представляет день, поэтому добавление 1 к дате добавит 1 день.

EOMONTH в Google Таблицах

Функция EOMONTH в Google Таблицах работает точно так же, как и в Excel:

EOMONTH Примеры в VBA

Вы также можете использовать функцию EOMONTH в VBA. Тип: application.worksheetfunction.eomonth (начальная_дата, месяцы)

Выполнение следующих инструкций VBA

123 Диапазон («B2») = Application.WorksheetFunction.EoMonth (Range («A2»), 0)Диапазон («B5») = Application.WorksheetFunction.EoMonth (Range («A5»), -1)Диапазон («B8») = Application.WorksheetFunction.EoMonth (Range («A8»), -1) + 1

Дадут следующие результаты

Для аргументов функции (начальная_дата и т. Д.) Вы можете либо ввести их непосредственно в функцию, либо определить переменные для использования вместо них.

Вернуться к списку всех функций в Excel

Вы поможете развитию сайта, поделившись страницей с друзьями

Вы можете использовать пользовательскую функцию GetLastDayOfMonth() и передайте интересующий вас диапазон:

Option Explicit

Public Function GetLastDayOfMonth(ByVal myDate As Date) As Date
    GetLastDayOfMonth = DateSerial(Year(myDate), Month(myDate) + 1, 0)
End Function

Public Sub TestMe()

    Range("A1") = DateSerial(2000, 11, 11)
    If Range("A1") = GetLastDayOfMonth(Range("A1")) Then
        Debug.Print "LAST DAY!"
    End If

    Range("A1") = DateSerial(2000, 12, 31)
    If Range("A1") = GetLastDayOfMonth(Range("A1")) Then
        Debug.Print "LAST DAY! " & Range("A1")
        Range("A1") = DateAdd("d", 1, Range("A1"))
    End If

End Sub

Функция проверяет месяц и год прошедшей даты и возвращает новую дату, которая является последним днем ​​месяца для этого конкретного месяца и года.

Тогда в TestMe Версия, вы можете сравнить заданную дату с последним днем ​​месяца, созданного функцией. Если даты совпадают, то эта дата является последним днем ​​соответствующего месяца. С помощью DateAdd() можно получить следующий день последнего дня.

В приведенном выше примере я явно написал Range(«A1») 9 раз, поэтому, вероятно, легче следовать.

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