Перейти к основному содержанию

Как быстро преобразовать дату в слова в Excel?

Как правило, мы обычно конвертируем дату в другие форматы даты или цифры в Excel, но сталкивались ли вы когда-нибудь с проблемой преобразования даты в английские слова, как показано на скриншоте ниже? На самом деле нет встроенной функции, которая могла бы с этим справиться, кроме кода VBA.
дата документа до слов 1

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


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

Вот код макроса, который может оказать вам услугу при преобразовании дат в слова.

1. Включите используемый лист и нажмите Alt + F11 ключи для открытия Microsoft Visual Basic для приложений окно.

2. Нажмите Вставить > Модули и вставьте ниже код в скрипт.

VBA: преобразовать дату в слово

Function DateToWords(ByVal xRgVal As Date) As String
' Update by Extendoffice on 20240926
    Dim xYear As String
    Dim Hundreds As String
    Dim Decades As String
    Dim xTensArr As Variant
    Dim xOrdArr As Variant
    Dim xCardArr As Variant
    
    ' Initialize arrays
    xOrdArr = Array("First", "Second", "Third", "Fourth", "Fifth", "Sixth", _
                    "Seventh", "Eighth", "Ninth", "Tenth", "Eleventh", "Twelfth", _
                    "Thirteenth", "Fourteenth", "Fifteenth", "Sixteenth", _
                    "Seventeenth", "Eighteenth", "Nineteenth", "Twentieth", _
                    "Twenty-first", "Twenty-second", "Twenty-third", "Twenty-fourth", _
                    "Twenty-fifth", "Twenty-sixth", "Twenty-seventh", "Twenty-eighth", _
                    "Twenty-ninth", "Thirtieth", "Thirty-first")
    
    xCardArr = Array("", "One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine", _
                    "Ten", "Eleven", "Twelve", "Thirteen", "Fourteen", "Fifteen", "Sixteen", _
                    "Seventeen", "Eighteen", "Nineteen")
    
    xTensArr = Array("Twenty", "Thirty", "Forty", "Fifty", "Sixty", "Seventy", "Eighty", "Ninety")
    
    ' Extract year
    xYear = CStr(Year(xRgVal))
    Decades = Mid$(xYear, 3)
    
    ' Handle decades
    If CInt(Decades) < 20 Then
        Decades = xCardArr(CInt(Decades))
    Else
        Decades = xTensArr(CInt(Left$(Decades, 1)) - 2) & "-" & xCardArr(CInt(Right$(Decades, 1)))
    End If
    
    ' Handle hundreds
    Hundreds = Mid$(xYear, 2, 1)
    If CInt(Hundreds) Then
        Hundreds = xCardArr(CInt(Hundreds)) & " Hundred "
    Else
        Hundreds = ""
    End If
    
    ' Construct English representation of the date
    DateToWords = xOrdArr(Day(xRgVal) - 1) & " " & Format$(xRgVal, "mmmm") & " " & _
                  xCardArr(CInt(Left$(xYear, 1))) & " Thousand " & Hundreds & Decades
End Function


дата документа до слов 2

3. Сохраните код и вернитесь к листу, выберите ячейку, в которой вы будете выводить результат, введите эту формулу. = DateToWords (A2) (A2 - используемая вами дата), нажмите Enter и перетащите маркер автозаполнения на нужные ячейки. Смотрите скриншот:
дата документа до слов 3дата документа до слов 4


Откройте для себя удобство мгновенного преобразования чисел в слова в Excel с помощью функции Kutools for Excel «Числа в слова», что сэкономит вам время и усилия при легком создании профессионально выглядящих документов!

Перейти к бесплатной загрузкеСкачать сейчас


Относительные статьи:

Лучшие инструменты для офисной работы

🤖 Kutools AI Помощник: Революционный анализ данных на основе: Интеллектуальное исполнение   |  Генерировать код  |  Создание пользовательских формул  |  Анализ данных и создание диаграмм  |  Вызов функций Kutools...
Популярные опции: Найдите, выделите или определите дубликаты   |  Удалить пустые строки   |  Объедините столбцы или ячейки без потери данных   |   Раунд без формулы ...
Супер поиск: Множественный критерий VLookup    VLookup с несколькими значениями  |   VLookup по нескольким листам   |   Нечеткий поиск ....
Расширенный раскрывающийся список: Быстрое создание раскрывающегося списка   |  Зависимый раскрывающийся список   |  Выпадающий список с множественным выбором ....
Менеджер столбцов: Добавить определенное количество столбцов  |  Переместить столбцы  |  Переключить статус видимости скрытых столбцов  |  Сравнить диапазоны и столбцы ...
Рекомендуемые функции: Сетка Фокус   |  Просмотр дизайна   |   Большой Формулный Бар    Менеджер книг и листов   |  Библиотека ресурсов (Авто текст)   |  Выбор даты   |  Комбинировать листы   |  Шифровать/дешифровать ячейки    Отправлять электронные письма по списку   |  Суперфильтр   |   Специальный фильтр (фильтровать жирным шрифтом/курсивом/зачеркиванием...) ...
15 лучших наборов инструментов12 Текст Инструменты (Добавить текст, Удалить символы, ...)   |   50+ График Тип (Диаграмма Ганта, ...)   |   40+ Практических Формулы (Рассчитать возраст по дню рождения, ...)   |   19 Вносимые Инструменты (Вставить QR-код, Вставить изображение из пути, ...)   |   12 Конверсия Инструменты (Числа в слова, Конверсия валюты, ...)   |   7 Слияние и разделение Инструменты (Расширенные ряды комбинирования, Разделить клетки, ...)   |   ... и более

Улучшите свои навыки работы с Excel с помощью Kutools for Excel и почувствуйте эффективность, как никогда раньше. Kutools for Excel предлагает более 300 расширенных функций для повышения производительности и экономии времени.  Нажмите здесь, чтобы получить функцию, которая вам нужна больше всего...

Описание


Вкладка Office: интерфейс с вкладками в Office и упрощение работы

  • Включение редактирования и чтения с вкладками в Word, Excel, PowerPoint, Издатель, доступ, Visio и проект.
  • Открывайте и создавайте несколько документов на новых вкладках одного окна, а не в новых окнах.
  • Повышает вашу продуктивность на 50% и сокращает количество щелчков мышью на сотни каждый день!
Comments (25)
No ratings yet. Be the first to rate!
This comment was minimized by the moderator on the site
The spelling of 9th is wrong. It's written Nineth, but it should be Ninth.
This comment was minimized by the moderator on the site
Thank you for your message. I have corrected and updated the code accordingly. Thank you.
This comment was minimized by the moderator on the site
07/08/1998 SEVENTH AUGUST TWENTY HUNDRED NINETY-EIGHT
In this vba have error
convert it1998 but it shows TWENTY HUNDRED NINETY-EIGHT
This comment was minimized by the moderator on the site
07/08/1998 SEVENTH AUGUST NINETEEN HUNDRED NINETY EIGHT
I need dob into words in upper format but i use this micros in excel i got this
07/08/1998 SEVENTH AUGUST ONE THOUSAND NINE HUNDRED NINETY-EIGHT which is not usefull
This comment was minimized by the moderator on the site
Hi, MAX, I have modified the VBA, please try and let me know if it works. Thanks.
Function DateToWords(ByVal xRgVal As Date) As String
'UpdatebyExtendoffice20170926
    Dim xYear As String
    Dim Decades As String
    Dim years As String
    Dim xTensArr As Variant
    Dim xyearArr As Variant
    Dim xOrdArr As Variant
    Dim xCardArr As Variant
    xOrdArr = Array("First", "Second", "Third", _
                   "Fourth", "Fifth", "Sixth", _
                   "Seventh", "Eighth", "Nineth", _
                   "Tenth", "Eleventh", "Twelfth", _
                   "Thirteenth", "Fourteenth", _
                   "Fifteenth", "Sixteenth", _
                   "Seventeenth", "Eighteenth", _
                   "Nineteenth", "Twentieth", _
                   "Twenty-first", "Twenty-second", _
                   "Twenty-third", "Twenty-fourth", _
                   "Twenty-fifth", "Twenty-sixth", _
                   "Twenty-seventh", "Twenty-eighth", _
                   "Twenty-nineth", "Thirtieth", _
                   "Thirty-first")
    xCardArr = Array("", "One", "Two", "Three", "Four", _
                   "Five", "Six", "Seven", "Eight", "Nine", _
                   "Ten", "Eleven", "Twelve", "Thirteen", _
                   "Fourteen", "Fifteen", "Sixteen", _
                   "Seventeen", "Eighteen", "Nineteen")
    xTensArr = Array("Twenty", "Thirty", "Forty", "Fifty", _
               "Sixty", "Seventy", "Eighty", "Ninety")
    xYear = CStr(Year(xRgVal))
    
    
      xyearArr = Array("", "One", "Two", "Three", "Four", _
                   "Five", "Six", "Seven", "Eight", "Nine", _
                   "Ten", "Eleven", "Twelve", "Thirteen", _
                   "Fourteen", "Fifteen", "Sixteen", _
                   "Seventeen", "Eighteen", "Nineteen", "Twenty", "Thirty", "Forty", "Fifty", _
               "Sixty", "Seventy", "Eighty", "Ninety")

    years = xyearArr(CInt(Year(xRgVal) / 100)) & " Hundred"
    
    Decades = Mid$(xYear, 3)
    If CInt(Decades) < 20 Then
        Decades = xCardArr(CInt(Decades))
    Else
        Decades = xTensArr(CInt(Left$(Decades, 1)) - 2) & "-" & _
                xCardArr(CInt(Right$(Decades, 1)))
    End If

    DateToWords = UCase(xOrdArr(Day(xRgVal) - 1) & _
                  Format$(xRgVal, " mmmm ") & _
                  years & " " & Decades)
End Function

This comment was minimized by the moderator on the site
07/08/1998 SEVENTH AUGUST TWENTY HUNDRED NINETY-EIGHT
In this vba have error
convert it1998 but it shows TWENTY HUNDRED NINETY-EIGHT
This comment was minimized by the moderator on the site
Hi, try this vba:
Function DateToWords(ByVal xRgVal As Date) As String
'UpdatebyExtendoffice20170926
    Dim xYear As String
    Dim Decades As String
    Dim years As String
    Dim xTensArr As Variant
    Dim xyearArr As Variant
    Dim xOrdArr As Variant
    Dim xCardArr As Variant
    xOrdArr = Array("First", "Second", "Third", _
                   "Fourth", "Fifth", "Sixth", _
                   "Seventh", "Eighth", "Nineth", _
                   "Tenth", "Eleventh", "Twelfth", _
                   "Thirteenth", "Fourteenth", _
                   "Fifteenth", "Sixteenth", _
                   "Seventeenth", "Eighteenth", _
                   "Nineteenth", "Twentieth", _
                   "Twenty-first", "Twenty-second", _
                   "Twenty-third", "Twenty-fourth", _
                   "Twenty-fifth", "Twenty-sixth", _
                   "Twenty-seventh", "Twenty-eighth", _
                   "Twenty-nineth", "Thirtieth", _
                   "Thirty-first")
    xCardArr = Array("", "One", "Two", "Three", "Four", _
                   "Five", "Six", "Seven", "Eight", "Nine", _
                   "Ten", "Eleven", "Twelve", "Thirteen", _
                   "Fourteen", "Fifteen", "Sixteen", _
                   "Seventeen", "Eighteen", "Nineteen")
    xTensArr = Array("Twenty", "Thirty", "Forty", "Fifty", _
               "Sixty", "Seventy", "Eighty", "Ninety")
    xYear = CStr(Year(xRgVal))
    
    
      xyearArr = Array("", "One", "Two", "Three", "Four", _
                   "Five", "Six", "Seven", "Eight", "Nine", _
                   "Ten", "Eleven", "Twelve", "Thirteen", _
                   "Fourteen", "Fifteen", "Sixteen", _
                   "Seventeen", "Eighteen", "Nineteen", "Twenty", "Thirty", "Forty", "Fifty", _
               "Sixty", "Seventy", "Eighty", "Ninety")

    years = xyearArr(Fix(Year(xRgVal) / 100)) & " Hundred"
    
    Decades = Mid$(xYear, 3)
    If CInt(Decades) < 20 Then
        Decades = xCardArr(CInt(Decades))
    Else
        Decades = xTensArr(CInt(Left$(Decades, 1)) - 2) & "-" & _
                xCardArr(CInt(Right$(Decades, 1)))
    End If

    DateToWords = UCase(xOrdArr(Day(xRgVal) - 1) & _
                  Format$(xRgVal, " mmmm ") & _
                  years & " " & Decades)
End Function

This comment was minimized by the moderator on the site
آپ کا بہت شکریہ
This comment was minimized by the moderator on the site
It is giving the #NAME? Error
This comment was minimized by the moderator on the site
I would like to add text to the output, for instance, 1958 gets converted to One Thousand Nineteen Hundred Fifty Eight and I would like it to say One Thousand Nineteen Hundred and Fifty Eight. Can someone give me an example of how I can do this please?
This comment was minimized by the moderator on the site
thank u for helping me . very useful in converting date of birth in word
This comment was minimized by the moderator on the site
Sir/Madam

It is very useful for me.

Really Amazing and helped to solve the problem within a minute.

Thank you for uploading this document. Very nice
This comment was minimized by the moderator on the site
how to use this code in vb6 for a textbox
This comment was minimized by the moderator on the site
date to word in gujarati language avilable ? please answer me. 9427909038
This comment was minimized by the moderator on the site
I think it does not work for other languages except english.
There are no comments posted here yet
Load More
Please leave your comments in English
Posting as Guest
×
Rate this post:
0   Characters
Suggested Locations