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

Как запустить или запустить макрос, щелкнув определенную ячейку в Excel?

Работая с Microsoft Excel, вы можете знать, как запускать определенный макрос с помощью командной кнопки. Но знаете ли вы, как запустить макрос, просто щелкнув определенную ячейку на листе? В этой статье будет подробно описан метод запуска макроса при нажатии на определенную ячейку.

Запуск или запуск макроса, щелкнув определенную ячейку с кодом VBA


Запуск или запуск макроса, щелкнув определенную ячейку с кодом VBA

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

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

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

Код VBA: запуск или запуск макроса, щелкнув определенную ячейку

Option Explicit

Private Sub Worksheet_SelectionChange(ByVal Target As Range)
    If Selection.Count = 1 Then
        If Not Intersect(Target, Range("D4")) Is Nothing Then
            Call MyMacro
        End If
    End If
End Sub

Заметки:

1. В коде D4 - это ячейка, по которой вы щелкаете, чтобы запустить макрос;

2. Пожалуйста, замените кодовое имя МойМакрос с макросом, который вы запустите на листе. Смотрите скриншот:

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

С этого момента при нажатии на ячейку D4 на текущем листе ваш указанный макрос будет запускаться немедленно.


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

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

🤖 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 (38)
No ratings yet. Be the first to rate!
This comment was minimized by the moderator on the site
Hi,
interesting, how can I adapt it for working on a cell that is a selection?
Basically I need to select a value from a cell (any value of a list) and then launch the macro, can you help me?
Thaks!
Corrado
This comment was minimized by the moderator on the site
Hola,

No encuentro la manera de hacer lo que necesito. Espero de veras que me podáis ayudar.
Necesito que se lance una MACRO al hacer clic en una celda, pero no sé en qué celda va a ser, no lo puedo comparar con (si se ha seleccionado la celda A3, por ejemplo, que se lance la acción) porque por funcionalidades del fichero, las celdas se van a mover de sitio (se han podido insertar, mas o menos filas encima). Necesitaría poder saber qué celda es la que se ha seleccionado.
Hay alguna manera de poder hacer eso?
Muchas gracias de antemano.
This comment was minimized by the moderator on the site
Hi Hola,
The cell address is constant. All you can move is the value of the cell.
The cell you specified in the VBA code is still the cell that trigger the specified VBA code.
This comment was minimized by the moderator on the site
I didn’t have any expectations concerning that title, but the more I was astonished. The author did a great job. I spent a few minutes reading and checking the facts. Everything is very clear and understandable. I like posts that fill in your knowledge gaps. This one is of the sort.
This comment was minimized by the moderator on the site
Grandioso! Grazie, era una vita che sognavo di poterlo fare, se può essere utile a qualcuno avendo necessità di eseguire più codici su più celle per
aumentare il numero di opzioni basta aggiungere le nuove istruzionisempre sotto la stessa option explicit altrimente ci viene detto che il riferimento al
worksheet non è univoco. Mi spiego meglio evidentemente su come ho adattato il codice con il mio esempio;

Option Explicit
Private Sub Worksheet_SelectionChange(ByVal Target As Range)
If Selection.Count = 1 Then
If Not Intersect(Target, Range("Y64")) Is Nothing Then
Range("Y65:Y78").Select
Range("Y65").Activate
Selection.ClearContents
Range("Y65").Select
End If
If Not Intersect(Target, Range("A33")) Is Nothing Then
Range("A33").Select
Selection.Copy
ActiveWindow.WindowState = xlMinimized
SendKeys "^v"
SendKeys "{BACKSPACE}"
End If
End If
End Sub

Grazie ancora è stata un'autentica meraviglia!

Massimo
This comment was minimized by the moderator on the site
For those wanting this to work for merged cells, the quickest and dirtiest way is to update Line 2 as follows:
<div data-tag="code">Option Explicit

Private Sub Worksheet_SelectionChange(ByVal Target As Range)
If Selection.Count > 0 Then
If Not Intersect(Target, Range("D4")) Is Nothing Then
Call MyMacro
End If
End If
End SubSelection.Count is being used to determine if a selection has been made before executing the remaining macro. If your selection consists of four cells that have been merged, Selection.Count will equal 4, and the remaining code will never execute.You can also change line 2 to the exact number of cells that were merged, but that will cause problems if you merge additional cells.
This comment was minimized by the moderator on the site
It is important to stress that the macro only runs in the worksheet.
Those of us who use the regular visual basic editor often end up storing macros in other places than in the current worksheet.
None of these codes will work in that situation.
I find this code to be much simpler and it works very well for me: 

Private Sub Worksheet_SelectionChange(ByVal Target As Excel.Range)
If Not Intersect(Range("d1"), Target) Is Nothing Then
Call aa
End If
End Sub
Sub aa() ' put your code here
Range("D1").Select
Selection.Copy
Range("F1").Select
ActiveSheet.PasteEnd Sub
John Wells
This comment was minimized by the moderator on the site
Hi John Wells,Thank you for sharing.
This comment was minimized by the moderator on the site
Does not work anymore.
Worksheet_SelectionChange does not exist by default. Meaning you cannot use that to trigger a macro.

The only embeded sub you can use are referenced in "Workbook" dropdown list, so...

The only closest thing you can do is using Workbook_SheetBeforeDoubleClick. But is will enter Edit mode (still not a big deal).
This comment was minimized by the moderator on the site
Hi CodeKiller.Worksheet_SelectionChange only exists in the Sheet(Code) editor. Right click the sheet tab and click View Code to activate the Sheet(Code) editor.
This comment was minimized by the moderator on the site
Hello, Thank you for your interesting subject. What if for example I want to to click on D4 in Sheet1 and see the result of Macro in Sheet2!F3.
This comment was minimized by the moderator on the site
hello, I was trying to use this code to Run a paste macro but can't seem to figure out how to paste the macro properly.

here is my original Marco

Sub Paste()
'
' Paste Macro
'

'
Range("B34").Select
ActiveSheet.PasteSpecial Format:="HTML", Link:=False, DisplayAsIcon:= _
False, NoHTMLFormatting:=True
End Sub


any help is appreciated
This comment was minimized by the moderator on the site
Thanks for this code. Is it possible to get this to work by clicking on a cell that is merged with others?
This comment was minimized by the moderator on the site
Hi M.Symonds,
The code in this article can do you a favor: https://www.extendoffice.com/documents/excel/4354-excel-click-on-cell-to-run-macro.html
Thank you for your comment.
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