Saltar al contenido principal

¿Cómo activar o ejecutar una macro haciendo clic en una celda específica en Excel?

Mientras trabaja con Microsoft Excel, es posible que sepa cómo ejecutar una determinada macro con un botón de comando. Pero, ¿sabe cómo ejecutar una macro simplemente haciendo clic en una celda específica en una hoja de trabajo? Este artículo le mostrará el método para activar una macro haciendo clic en una celda específica en detalles.

Active o ejecute una macro haciendo clic en una celda específica con código VBA


Active o ejecute una macro haciendo clic en una celda específica con código VBA

El siguiente código de VBA puede ayudarlo a ejecutar una macro haciendo clic en una celda específica en Excel. Haz lo siguiente.

1. En la hoja de trabajo con la celda en la que necesita hacer clic para ejecutar una macro, haga clic con el botón derecho en la pestaña de la hoja y luego haga clic en Ver código desde el menú contextual.

2. En el Microsoft Visual Basic para aplicaciones ventana, copie y pegue el siguiente script VBA en la ventana Código.

Código de VBA: active o ejecute una macro haciendo clic en una celda específica

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

Notas:

1. En el código, D4 es la celda en la que hará clic para ejecutar Macro;

2. Reemplace el nombre del código MiMacro con la macro se ejecutará en la hoja de trabajo. Ver captura de pantalla:

3. presione el otro + Q teclas simultáneamente para cerrar el Microsoft Visual Basic para aplicaciones ventana.

De ahora en adelante, al hacer clic en la celda D4 en la hoja de trabajo actual, su macro especificada se activará inmediatamente.


Artículos relacionados:

Las mejores herramientas de productividad de oficina

🤖 Asistente de IA de Kutools: Revolucionar el análisis de datos basado en: Ejecución inteligente   |  Generar codigo  |  Crear fórmulas personalizadas  |  Analizar datos y generar gráficos  |  Invocar funciones de Kutools...
Características populares: Buscar, resaltar o identificar duplicados   |  Eliminar filas en blanco   |  Combine columnas o celdas sin perder datos   |   Ronda sin fórmula ...
Super búsqueda: Búsqueda virtual de criterios múltiples    Búsqueda V de valores múltiples  |   VLookup en varias hojas   |   Búsqueda difusa ....
Lista desplegable avanzada: Crear rápidamente una lista desplegable   |  Lista desplegable dependiente   |  Lista desplegable de selección múltiple ....
Administrador de columnas: Agregar un número específico de columnas  |  Mover columnas  |  Toggle Estado de visibilidad de columnas ocultas  |  Comparar rangos y columnas ...
Características destacadas: Enfoque de cuadrícula   |  Vista de diseño   |   Gran barra de fórmulas    Administrador de hojas y libros de trabajo   |  Biblioteca de Recursos (Texto automático)   |  Selector de fechas   |  Combinar hojas de trabajo   |  Cifrar/descifrar celdas    Enviar correos electrónicos por lista   |  Súper filtro   |   Filtro especial (filtro negrita/cursiva/tachado...) ...
Los 15 mejores conjuntos de herramientas12 Texto Herramientas (Añadir texto, Quitar caracteres, ...)   |   50+ Tabla Tipos (Diagrama de Gantt, ...)   |   40+ Práctico Fórmulas (Calcular la edad según el cumpleaños, ...)   |   19 Inserción Herramientas (Insertar código QR, Insertar imagen desde la ruta, ...)   |   12 Conversión Herramientas (Números a palabras, Conversión de Moneda, ...)   |   7 Fusionar y dividir Herramientas (Filas combinadas avanzadas, Células partidas, ...)   |   ... y más

Mejore sus habilidades de Excel con Kutools for Excel y experimente la eficiencia como nunca antes. Kutools for Excel ofrece más de 300 funciones avanzadas para aumentar la productividad y ahorrar tiempo.  Haga clic aquí para obtener la función que más necesita...

Descripción


Office Tab lleva la interfaz con pestañas a Office y hace que su trabajo sea mucho más fácil

  • Habilite la edición y lectura con pestañas en Word, Excel, PowerPoint, Publisher, Access, Visio y Project.
  • Abra y cree varios documentos en nuevas pestañas de la misma ventana, en lugar de en nuevas ventanas.
  • ¡Aumenta su productividad en un 50% y reduce cientos de clics del mouse todos los días!
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