Vba excel название месяца по номеру

OBJECTS
Worksheets: The Worksheets object represents all of the worksheets in a workbook, excluding chart sheets.
Range: The Range object is a representation of a single cell or a range of cells in a worksheet.

PREREQUISITES
Worksheet Name: Have a worksheet named Analysis.
Number Rage: In this example we are converting numbers in range («B5:B16») into month names. Therefore, if you are using this exact VBA code you will need to capture all the numbers in range («B5:B16») that you want to convert into a month name.

ADJUSTABLE PARAMETERS
Output Range: Select the output range by changing the cell reference («C5») in the VBA code to any cell in the worksheet, that doesn’t conflict with the formula.
Number Rage: Select the range that captures the numbers that you want to convert into month names by changing the range reference («B5:B16») in the VBA code to any range in the worksheet that doesn’t conflict with the formula. If you change the number or location of rows then you will need to change the parameters that is driving the For Loop. In this case its the values that we have nominated for x, which are from 5 to 16.

25 / 0 / 0

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

Сообщений: 11

1

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

16.10.2011, 11:43. Показов 13609. Ответов 4


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

Никак не могу разобраться как в VBA осуществить данную задачу:»С 1 января 1990 года по некоторый день прошло m месяцев и n дней, определить название текущего месяца.»



0



Programming

Эксперт

94731 / 64177 / 26122

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

Сообщений: 116,782

16.10.2011, 11:43

Ответы с готовыми решениями:

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

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

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

Написать программу, которая по номеру месяца выдает название следующего за ним месяца
Хотел сделать что-то простое, но не понимаю почему выдаёт ошибку, с m Mod 13 работает, помогите…

4

dzug

695 / 236 / 18

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

Сообщений: 583

Записей в блоге: 1

16.10.2011, 11:50

2

Можно так

Visual Basic
1
2
3
4
5
6
7
Function dhMonthName(intMonth As Integer) As String
   ' Возвращение имени месяца по его номеру (intMonth _
   ' является номером элемента в массиве с названиями месяцев)
   dhMonthName = Choose(intMonth, "Январь", "Февраль", "Март", _
    "Апрель", "Май", "Июнь", "Июль", "Август", "Сентябрь", _
    "Октябрь", "Ноябрь", "Декабрь")
End Function

или
MonthName() — возвращает имя месяца словами по его номеру. Возвращаемое значение зависит от региональных настроек. Если они русские, то вернется русское название месяца.



2



Апострофф

Заблокирован

16.10.2011, 12:09

3

Visual Basic
1
msgbox array("янв","фев","мар","апр","май","июн","июл","авг","сен","окт","ноя","дек")(m-1)

Добавлено через 18 минут
А если m=13 и n=32?

Visual Basic
1
msgbox monthname(month(dateadd("d",n,dateadd("m",m,"1.1.1990"))))



0



Казанский

15136 / 6410 / 1730

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

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

16.10.2011, 16:11

4

Для определения названия месяца можно не использовать самодельную функцию:

Visual Basic
1
2
3
4
5
6
Sub MonName()
Dim n, m
n = -10
m = 17
MsgBox Format(DateAdd("d", n, DateAdd("m", m, "1.1.1990")), "MMMM")
End Sub

Будет выведен месяц на языке локали.



1



Sasha_Smirnov

5561 / 1367 / 150

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

Сообщений: 4,107

Записей в блоге: 30

16.10.2011, 16:47

5

Visual Basic
1
2
3
4
5
6
7
8
9
10
11
Sub DateParts()
Const M = 5     'сюда ставим количество прошедших месяцев
Const N = 10    'сюда ставим количество прошедших дней
Dim CurrentDate As Date
CurrentDate = DateAdd("m", M, #1/1/1990#) + N 'добавили M месяцев и N дней
 
MsgBox CurrentDate                      'показ получившейся даты
MsgBox DatePart("yyyy", CurrentDate)    'показ её года
MsgBox MonthName(Month(CurrentDate))    'показ названия её месяца (что мы и ищем)
MsgBox DatePart("d", CurrentDate)       'показ числа месяца
End Sub



2



Month plays an important role of a date. We can get month name from date in different ways. We can get month name using MonthName function and summarize data with it. Format name of the month by using format function.

Let us see the procedure how to get name of the month from today’s date using MonthName function.

'Procedure to Get Month Name From Date
Sub VBA_Get_Month_Name()
    
    'Variable declaration
    Dim sMonth_Name As String
    
    'Retrieve month Name from date
    sMonth_Name = MonthName(Month("01/01/2018"))

    'Display month name
    MsgBox "If Date is "01/01/2018" then" & vbCrLf & _
    "Month name is : " & sMonth_Name, vbInformation, "Month Name From Date"
    
End Sub

Explanation: In the above procedure we have used Month, Date and MonthName VBA functions. Here Month function is used to display month number. MonthName function helps to generate name of the month from specified month number. Here is the output screenshot for your reference.

VBA Get Month Name

Format Name of the Month:

We have different format methods to format name of the month. You can find output in an immediate window.

'Format Name of the Month
Sub VBA_Format_Month_Name()
    
    'Variable declaration
    Dim sMonth_Name As String
    
    sMonth_Name = Format("01/01/2018", "m")
    Debug.Print sMonth_Name
    
    sMonth_Name = Format("01/01/2018", "mm")
    Debug.Print sMonth_Name
    
    sMonth_Name = Format("01/01/2018", "mmm")
    Debug.Print sMonth_Name
    
    sMonth_Name = Format("01/01/2018", "mmmm")
    Debug.Print sMonth_Name
        
End Sub

Output screenshot: Here is the output screenshot.
Format Month Name

Instructions to Run VBA Macro Code or Procedure:

You can refer the following link for the step by step instructions.

Instructions to run VBA Macro Code

Other Useful Resources:

Click on the following links of the useful resources. These helps to learn and gain more knowledge.

VBA Tutorial VBA Functions List VBA Arrays VBA Text Files VBA Tables

VBA Editor Keyboard Shortcut Keys List VBA Interview Questions & Answers Blog

Home / VBA / Top VBA Functions / VBA MONTHNAME Function (Syntax + Example)

The VBA MONTHNAME function is listed under the date and time category of VBA functions. When you use it in a VBA code, it returns the month name as a string from a valid date as per VBA. In simple words, you can extract the month value of a name from a date supplied.

MonthName(Month, [Abbreviate])

Arguments

  • Month: an integer (ranging from 1 to 12) representing the month.
  • [Abbreviate]: A boolean value to specify if you need to a full name of the month or an abbreviated name [This is an optional argument and if omitted VBA takes FALSE by default].
    • Use TRUE for the abbreviated name (i.e. “Jan”, “Feb”, “Mar”, etc.) or FALSE for the full name (i.e. “January”, “February”, “March”, etc.) 

Example

To practically understand how to use the VBA MONTHNAME function, you need to go through the below example where we have written a vba code by using it:

Sub example_MONTHNAME()
Range("B1").Value = MonthName(Range("A1"), False)   
End Sub

In the above code, we have used the MONTHNAME to get the name of the month as per the value in cell A1 and we have a 1 in cell A1 so it has returned the “January”.

Notes

  • If the value specified as the month is other than an integer or a string that can’t be recognized as a number, VBA will return the run-time 13 error.

totn Excel Functions


This Excel tutorial explains how to use the Excel MONTHNAME function with syntax and examples.

Description

The Microsoft Excel MONTHNAME function returns a string representing the month given a number from 1 to 12.

The MONTHNAME function is a built-in function in Excel that is categorized as a Date/Time Function. It can be used as a VBA function (VBA) in Excel. As a VBA function, you can use this function in macro code that is entered through the Microsoft Visual Basic Editor.

Syntax

The syntax for the MONTHNAME function in Microsoft Excel is:

MonthName( number, [ abbreviate ] )

Parameters or Arguments

number
A value from 1 to 12, representing the month.
abbreviate
Optional. This parameter accepts a boolean value, either TRUE or FALSE. If this parameter is set to TRUE, it means that the month name is abbreviated. If this parameter is set to FALSE, the month name is not abbreviated. If this parameter is omitted, it defaults to FALSE.

Returns

The MONTHNAME function returns a string value.

Applies To

  • Excel for Office 365, Excel 2019, Excel 2016, Excel 2013, Excel 2011 for Mac, Excel 2010, Excel 2007, Excel 2003, Excel XP, Excel 2000

Type of Function

  • VBA function (VBA)

Example (as VBA Function)

The MONTHNAME function can only be used in VBA code in Microsoft Excel.

Let’s look at some Excel MONTHNAME function examples and explore how to use the MONTHNAME function in Excel VBA code:

MonthName(3)
Result: 'March'

MonthName(3, TRUE)
Result: 'Mar'

MonthName(7, FALSE)
Result: 'July'

For example:

Dim LValue As String

LValue = MonthName(3, TRUE)

In this example, the variable called LValue would now contain the value of ‘Mar’.

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