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

Как автоматически добавить / ввести текущую дату / время в ячейку двойным щелчком в Excel?

Если вам нужно часто вставлять текущую дату или дату и время на лист, вы можете попробовать метод, описанный в этой статье. Эта статья поможет вам автоматически добавлять или вводить текущую дату или дату в ячейках указанного диапазона с помощью только двойного щелчка.

Дважды щелкните, чтобы автоматически добавить / ввести текущую дату или дату и время с кодом VBA


Дважды щелкните, чтобы автоматически добавить / ввести текущую дату или дату и время с кодом VBA

Вы можете запустить приведенный ниже код VBA, чтобы автоматически добавить текущую дату или дату и время в ячейку двойным щелчком. Пожалуйста, сделайте следующее.

1. Щелкните правой кнопкой мыши вкладку «Лист», на которой вы хотите вставить текущую дату в указанные ячейки, затем выберите Просмотреть код из контекстного меню.

2. в Microsoft Visual Basic для приложений окна, скопируйте и вставьте приведенный ниже код VBA в окно кода.

Код VBA: дважды щелкните, чтобы добавить текущую дату в ячейку

Private Sub Worksheet_BeforeDoubleClick(ByVal Target As Range, Cancel As Boolean)
    If Not Intersect(Target, Range("A1:B10")) Is Nothing Then
        Cancel = True
        Target.Formula = Date
    End If
End Sub

Заметки:

1. В коде A1: B10 - это диапазон, в который вы добавите текущую дату.
2. Если вам нужно добавить текущую дату и время в ячейку, замените Время Теперь() в коде. Вы можете изменить их по своему усмотрению.

3. Нажмите другой + Q клавиши одновременно, чтобы закрыть Microsoft Visual Basic для приложений окно и вернитесь к рабочему листу.

С этого момента при двойном щелчке по любой ячейке в указанном диапазоне A1: B10. Текущая дата или дата и время будут введены автоматически.


Статьи по теме:

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

🤖 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 (30)
No ratings yet. Be the first to rate!
This comment was minimized by the moderator on the site
Hello. How do I enter the code so I can insert the date in a cell and the time in the adjacent row?
This comment was minimized by the moderator on the site
Holy crap MS get with it! Google sheets can make this happen with a couple of clicks.
This comment was minimized by the moderator on the site
Hi all,

I try to use that macro to use the date stamp double clicking on column E and it's working but when I try to replicate the macro to do the same but for the current time on column F it is not working as you can see attached I have an error message stating : Ambiguous Name Detected.
When I try to change the Sub WorkSheet part for another name and double click in the cells nothing happens.

Could someone help me on that ?

My code :


Sub Worksheet_BeforeDoubleClick(ByVal Target As Range, Cancel As Boolean)
If Not Intersect(Target, Range("E1:E10000")) Is Nothing Then
Cancel = True
Target.Formula = Date
End If
End Sub

Sub Worksheet_BeforeDoubleClick(ByVal Target As Range, Cancel As Boolean)
If Not Intersect(Target, Range("F1:F10000")) Is Nothing Then
Cancel = True
Target.Formula = Now()
End If
End Sub
This comment was minimized by the moderator on the site
Hi Louis,
Replicate the macro will cause two same procedures with the same name in a single sheet code window. Excel doesn't allow two or more same names of functions in a module. Not even in Events. It leads to ambiguity.
If you want to do a different task on the same event, you need to modify the original code to meet your needs.
The following VBA code can do you a favor. Please give it a try.
Sub Worksheet_BeforeDoubleClick(ByVal Target As Range, Cancel As Boolean)
'Updated by Extendoffice 20221025
    If Not Intersect(Target, Range("E1:E10000")) Is Nothing Then
        Cancel = True
        Target.Formula = Date
    End If
    If Not Intersect(Target, Range("F1:F10000")) Is Nothing Then
        Cancel = True
        Target.Formula = Date
    End If
End Sub
This comment was minimized by the moderator on the site
This function did not work. Double Clicking simply enters manual edit of cell.
This comment was minimized by the moderator on the site
Hi Bob,
The code works well in my case. I need to know more specific about your issue, such as your Excel version.
And the code only works on the cells you specified.
This comment was minimized by the moderator on the site
Hello there, the code did a lot for me, How can I restrict the code to work only if field is blank. If a date is already there in the cell, double click should do nothing, regards
This comment was minimized by the moderator on the site
Hi Ahmad,
Sorry for the trouble. To only fill in the blank cells with dates with double-clicking, you can apply the following VBA code to get it done.
Private Sub Worksheet_BeforeDoubleClick(ByVal Target As Range, Cancel As Boolean)
'Updated by Extendoffice 20220609
    If Not Intersect(Target, Range("B1:C20")) Is Nothing Then
        If Target.Value = "" Then
            Cancel = True
            Target.Formula = Date
        End If
    End If
End Sub
This comment was minimized by the moderator on the site
This was just what I was looking for - this save a ton of time and I appreciate the well written instructions. Thank you!
This comment was minimized by the moderator on the site
So I inserted code and it works great on several sheets in my workbook, however on some sheets it just suddenly stops working after a certain row even though I have the correct range entered. Any thoughts on why this might happen.
This comment was minimized by the moderator on the site
Does anyone know if there is a way to insert this code into Excel Online? I had used it with the desktop version and it worked great but now we have migrated everything to the online platform and my date and time stamps on double click have disappeared and I can't figure out how to view or edit the code. Thanks.
This comment was minimized by the moderator on the site
Love the code and it works great. How can I make it so when I double click to execute the code its shows time in military time?
This comment was minimized by the moderator on the site
I would think that if you just select the Military Time format for that cell from the Number -> Time format options that should do it. For example, you would select 13:30 instead of 1:30 PM, and then it should display in military time.
This comment was minimized by the moderator on the site
I think if you select the military time format for that cell from the Format -> Number -> Time options in your sheet that ought to work. For example, it gives the option of 1:30 PM or 13:30, so you would just select 13:30 and that should do it.
This comment was minimized by the moderator on the site
Hi Dylan,
Sorry can't help you with that yet. Thank you for your comment.
This comment was minimized by the moderator on the site
Hi there,

I copied and pasted the above code exactly as it is written into a blank workbook, however, it does not work for me. I looked at different sources on the web and most sites have a similar format as what is written above. I think perhaps there is something wrong with my VBA or some settings are not turned on. Any advice would be much appreciated. I am running Excel for Office 365 MSO (16.0.11001.20097) 32-bit on Windows 10.
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