Saltar al contenido principal

¿Cómo ocultar o mostrar un botón de comando según el valor de celda especificado en Excel?

Supongamos que está utilizando un botón de comando para activar un script VBA en su hoja de trabajo. Cuando el script de VBA no se usa en algunos casos, debe ocultar el Botón de comando en lugar de mostrarlo en la hoja de trabajo. Y vuelva a mostrarlo cuando se necesite el script VBA. Este artículo habla de ocultar o mostrar un botón de comando basado en un valor de celda específico en Excel. Haz lo siguiente.

Ocultar o mostrar un botón de comando según el valor de celda especificado con código VBA


Ocultar o mostrar un botón de comando según el valor de celda especificado con código VBA

Puede ejecutar el siguiente código VBA para ocultar o mostrar un Botón de comando según el valor de celda especificado en Excel.

1. Haga clic con el botón derecho en la pestaña de la hoja que contiene el botón de comando que necesita mostrar ocultar, luego haga clic en Ver código desde el menú contextual.

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

Código de VBA: oculte o muestre un botón de comando según el valor de celda especificado

Private Sub Worksheet_Change(ByVal Target As Range)
    Application.ScreenUpdating = False
    If Cells(1, 1).Value <> "1" Then
        Me.CommandButton1.Visible = True
    Else
        Me.CommandButton1.Visible = False
    End If
    Application.ScreenUpdating = True
End Sub

Note: en el código, Celdas (1, 1), 1 y Botón de comando1 indican que CommandButton1 se ocultará cuando la celda A1 contenga el número 1 y se mostrará si la celda A1 contiene otros valores excepto el número 1. Vea la captura de pantalla siguiente. Y puede cambiarlos según sus necesidades.


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 (14)
No ratings yet. Be the first to rate!
This comment was minimized by the moderator on the site
Cool idea. Pity it doesn't work :(
This comment was minimized by the moderator on the site
Der Code funktioniert wie er ist prima.
Ich würde nur gerne den Button bei jeder 0 und leeren Zelle ausblenden lassen. Irgendwie bekomme ich es nicht hin. Es funktioniert immer nur entweder oder. Könnten Sie mir bitte weiter helfen danke
This comment was minimized by the moderator on the site
Hi Christoph,

Sorry I don't understand what you mean. For clarity, please attach a sample file or a screenshot with your data and desired results.
This comment was minimized by the moderator on the site
Hola!
Alguien sabe como puedo hacer para que el boton comando aparezca o desaparezca segun información de otra hoja?
El ejemplo está muy bueno, pero las celdas son de la misma hoja donde esta el boton. Yo necesito ocultar un boton segun info de otra hoja.

Gracias!
This comment was minimized by the moderator on the site
Hi,
Suppose, the value used to display or hide the command button locates in A1 of Sheet1, and the comman button locates in Sheet2. Please open the Sheet1, right click the sheet tab and click View Code. In the opening Microsoft Visual Basic for Applications window, copy the following VBA code into the Sheet1 (Code) window, and then press the Alt + F11 keys to close it.
Note: Please change Cells(1, 1), "1" and "Sheet2" as you need.
Private Sub Worksheet_Change(ByVal Target As Range)
    Application.ScreenUpdating = False
    If Cells(1, 1).Value <> "1" Then
        Sheets("Sheet2").CommandButton1.Visible = True
    Else
        Sheets("Sheet2").CommandButton1.Visible = False
    End If
    Application.ScreenUpdating = True
End Sub
This comment was minimized by the moderator on the site
hola, el codigo esta bien? es que no me funciona y ya intente varias cosas para que funcione y nana, ayuda por favor es que lo necesito para algo importante :c
This comment was minimized by the moderator on the site
For some reason after the button go from invisible back to visible, the button no longer works. If I alt + F11 into the code select the XXX() sub and run with F5 the code works for my macro. Why doesn't it work when i click the button anymore? in properties 'Enabled' is set to true
This comment was minimized by the moderator on the site
Private Sub Worksheet_Change(ByVal Target As Range)
Application.ScreenUpdating = False
If Cells(1, 1).Value <> "1" Then
Me.Shapes("Button 1").Visible = True
Else
Me.Shapes("Button 1") End If
Application.ScreenUpdating = True
End Sub
This comment was minimized by the moderator on the site
Hello

I am new to VBA, I have put this code into a new Excel. One CommnadButton, on Sheet1 but the code doesnt work.

Do I have to do anything before this?


Thanks in Advance
This comment was minimized by the moderator on the site
Use the ActiveX Control Button.
This comment was minimized by the moderator on the site
I've put this code in and entered my button name (Finish), referenced the reference cell (P11 - 16, 11) but every time I make a change to the reference cell (P11) I get a compile error and it highlights the ".Finish" section of the code, seemingly meaning the button name I entered "Finish" is not found on the worksheet. I've confirmed, both in the drop down area to the left of the formula bar and in the "define name" area on the Formula tab that my button name is, in fact, "Finish", but it still does not work.


Any help?
This comment was minimized by the moderator on the site
Hi Bryce,
I changed the button name to "Finish" in my worksheet, and it works well without any error displaying.
Do you mind testing the code in a new blank workbook?
Thank you for your comment.
This comment was minimized by the moderator on the site
hola que tal, tengo un boton con macro, que me devuelve a una hoja 'menu', pero no quiero que ese boton aparezca en la hoja menu como le puedo hacer?'


saludos.-
This comment was minimized by the moderator on the site
Hola Sebastia,

Dónde debería mostrarse?
- Uno es la hoja de menú
- El botón está integrado en una hoja diferente, no?
There are no comments posted here yet
Please leave your comments in English
Posting as Guest
×
Rate this post:
0   Characters
Suggested Locations