Saltar al contenido principal

¿Cómo ocultar o mostrar una determinada forma según el valor de celda especificado en Excel?

En realidad, una determinada forma puede ocultarse o mostrarse según el valor de una celda específica. El siguiente método puede ayudarte.

Ocultar o mostrar una determinada forma según el valor de celda especificado con el código VBA


Ocultar o mostrar una determinada forma según el valor de celda especificado con el código VBA

Por ejemplo, desea mostrar una determinada forma al ingresar el número 1 en la celda A1 u ocultar esta forma si la celda A1 tiene otros valores. Ejecute el siguiente código VBA para lograrlo.

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

2. Entonces el Microsoft Visual Basic para aplicaciones aparece la ventana. Copie y pegue el siguiente código VBA en el Código ventana.

Código de VBA: oculte o muestre una determinada forma según el valor de celda especificado

Private Sub Worksheet_Change(ByVal Target As Range)
    If Target.Row = 1 And Target.Column = 1 Then _
        Me.Shapes("Oval 6").Visible = (Cells(1, 1).Value = 1)
End Sub

Notas: En el código:

1) Fila = 1 y Columna = 1 indique la celda específica que se encuentra en la fila uno y la columna uno, Celdas (1, 1) es la celda correspondiente A1.
2) Valor = 1, el número 1 es el valor específico en el que desea mostrar la forma.
3) "Oval 6”Es el nombre de la forma determinada.

Puede cambiarlos según sus necesidades.

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

De ahora en adelante, al ingresar el número 1 en la celda A1, la forma "Oval 6" se muestra sin ocultar. Pero si ingresa otro valor como el número 2 en la celda A1, la forma "Oval 6" se oculta 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 (14)
No ratings yet. Be the first to rate!
This comment was minimized by the moderator on the site
Hello,

thank you for making this guide!

I have one question:
If i need a shape to show up based on two or more values, how is this done?
This comment was minimized by the moderator on the site
Hi Kasper Pedersen,

Suppose you want to show up a shape named "Oval 4" when both cells A1 and C8 contain the specified values (1 and 2 respectively), and if either of the cells is cleared (i.e., its value becomes empty), the shape will set to invisible. You can try the following VBA code to get it done.

Private Sub Worksheet_Change(ByVal Target As Range)
    If Range("A1").Value = 1 And Range("C8").Value = 2 Then
        Me.Shapes("Oval 4").Visible = True
    ElseIf Range("A1").Value = "" Or Range("C8").Value = "" Then
        Me.Shapes("Oval 4").Visible = False
    End If
End Sub
This comment was minimized by the moderator on the site
Thanks, but i want the shape not to be visible if the value is diffrent than "1" and "2" as shown in your example. eg. if the value is diffrent from 1 in cell A1 the shape becomes invisible. Is it possible?
This comment was minimized by the moderator on the site
This article doesn't give any hint as to how one gets the name of a shape.

I have checked the name manager and the object manager in VBA as well as the context menu - there is no "Properties" menu for shapes.

So, where is the shape name?
This comment was minimized by the moderator on the site
Hi Cornan,
The shape name will be displayed on the Name box of worksheet when selecting the shape. Sorry for the inconvenience.
This comment was minimized by the moderator on the site
2 questions:

1. I cant seem to get this code to run and i dont understand why... copied and pasted it exactly as it is there...help!!!


2. how do i change it for shapes like Shapes.Range(Array("Rounded Rectangle 1"))
This comment was minimized by the moderator on the site
Hi Gus,
You must miss something in the operation.
Supposing your shape name is "Rounded Rectangle 1", please copy the below code into the worksheet code window (this worksheet should contain the specified shape "Rounded Rectangle 1").
From now on, only typing number 1 into A1 cell can display the shape "Rounded Rectangle 1". If you type in other content, the shape will be hidden.

Private Sub Worksheet_Change(ByVal Target As Range)
If Target.Row = 1 And Target.Column = 1 Then _
Me.Shapes("Rounded Rectangle 1").Visible = (Cells(1, 1).Value = 1)
End Sub
This comment was minimized by the moderator on the site
You left out the ":"
This comment was minimized by the moderator on the site
I am a newbie in VBA Excel. I am working with this code and I would like to optimize it. This code makes a shape visible on an active cell if value is 1 other values hide it. Range includes J13:AC161. If I will use the code below, it will take me more lines of code. Any help will be much appreciated.

Private Sub Worksheet_Change(ByVal Target As Range)
If ActiveSheet.Range("E13").Value = 1 Then
ActiveSheet.Shapes("rt1").Visible = True
Else
ActiveSheet.Shapes("rt1").Visible = False
End If

If ActiveSheet.Range("F13").Value = 1 Then
ActiveSheet.Shapes("rt2").Visible = True
Else
ActiveSheet.Shapes("rt2").Visible = False
End If

If ActiveSheet.Range("G13").Value = 1 Then
ActiveSheet.Shapes("rt3").Visible = True
Else
ActiveSheet.Shapes("rt3").Visible = False
End If

If ActiveSheet.Range("H13").Value = 1 Then
ActiveSheet.Shapes("rt4").Visible = True
Else
ActiveSheet.Shapes("rt4").Visible = False
End If

If ActiveSheet.Range("I13").Value = 1 Then
ActiveSheet.Shapes("rt5").Visible = True
Else
ActiveSheet.Shapes("rt5").Visible = False
End If

If ActiveSheet.Range("J13").Value = 1 Then
ActiveSheet.Shapes("rt6").Visible = True
Else
ActiveSheet.Shapes("rt6").Visible = False
End If
...

End Sub
This comment was minimized by the moderator on the site
Good day,
Do you mean you want to display or hide lots of specified shapes based on cells in range J13:AC161 with brief code?
This comment was minimized by the moderator on the site
This works great for me as long as the value entered is a number. I need it to work on letters like A B C etc: when i use letters it works backwards enter A and it hides i need it to be visible when i enter a letter any ideas
This comment was minimized by the moderator on the site
You can use letters instead, you just need to add " to either side. E.g. Me.Shapes("Oval 6").Visible = (Cells(1, 1).Value = "A")
This comment was minimized by the moderator on the site
How about if i want to add two values as the input such as : E.g. Me.Shapes("Oval 6").Visible = (Cells(1, 1).Value = "A" Or "B")?
This comment was minimized by the moderator on the site
Me.Shapes("Rounded Rectangle 2").Visible = (Cells(1, 1).Value = "A" Or Cells(1, 1).Value = "B")
There are no comments posted here yet
Please leave your comments in English
Posting as Guest
×
Rate this post:
0   Characters
Suggested Locations