Saltar al contenido principal

¿Cómo cambiar el valor según el color de la celda en Excel?

Este artículo habla de cambiar el valor de la celda automáticamente en función de su color de fondo en Excel. Por ejemplo, si las celdas se llenan con color de fondo rojo en la selección, entonces complete estas celdas con el número 1, y para las celdas de color de fondo azul, complete el número 0.

Cambiar el valor según el color de la celda con el código VBA


Cambiar el valor según el color de la celda con el código VBA

Puede ejecutar el siguiente código VBA para cambiar el valor según el color de la celda en Excel. Haz lo siguiente.

1. Seleccione el rango que necesita para cambiar los valores según el color de fondo, luego presione otro + F11 teclas simultáneamente para abrir el Microsoft Visual Basic para aplicaciones ventana.

2. En el Microsoft Visual Basic para aplicaciones ventana, haga clic recuadro > Módulo, luego copie y pegue el siguiente código VBA en la ventana del Módulo.

Código de VBA: cambie el valor según el color de la celda en Excel

Sub ChangeValueBasedOnCellColor()
    Dim rg As Range
    Dim xRg As Range
    Set xRg = Selection.Cells
    Application.DisplayAlerts = False
    For Each rg In xRg
        With rg
            Select Case .Interior.Color
                Case Is = 255 'Red
                    .Value = 1
                Case Is = 15773696 'Blue
                    .Value = 0
            End Select
        End With
    Next
    Application.DisplayAlerts = False
End Sub

3. presione el F5 para ejecutar el código, entonces puede ver que todas las celdas rojas en el rango seleccionado están llenas con el número 1, y las celdas azules están llenas con el número 0 como se muestra a continuación.

 

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 (11)
No ratings yet. Be the first to rate!
This comment was minimized by the moderator on the site
Is there a way to do this, but have it automatically go through multiple files?
For context, questionnaires were sent to a couple hundred facilities, their MC answer selected corresponds to a color indicating score (e.g. green is good, red is bad), and change the content of the cell (with a process like in this thread) to something that R or another software could read, and then use that to generate automatic reports. I could go through each of these files with this macro (or a completely different idea), but that would take a long time.
This comment was minimized by the moderator on the site
The code works fine for me, but I would need to rewrite the code to fit colours specific for my document. But I don´t know what code "my colours" have, anyone who know where on can find codes for other colours?
This comment was minimized by the moderator on the site
I came across this lucky strike which was helpful but don't know where to find a full directory!
http://cdn-0.access-excel.tips/wp-content/uploads/2015/08/excel_vbcolor_10.png 
This comment was minimized by the moderator on the site
How do you run it, i run but nothing seems to happen
This comment was minimized by the moderator on the site
You can replace colors to values by simply using Find and Replace function. Go to the format function on the right side of the Find and Replace dialog box and then under "Fill" you can select the color that you have. Then on the "replace with" just write the value you want.
This comment was minimized by the moderator on the site
is it possible to adjust this code based on the cells conditional formatting rule?
This comment was minimized by the moderator on the site
Excel seems to crash whenever I try to run the VBA code. Seems like a bust.
This comment was minimized by the moderator on the site
Good day,
The code works well in my case. Can you tell me your Excel version? Thank you for your comment.
This comment was minimized by the moderator on the site
I'm in the same boat, trying to run this but the code seems to get hung. Excel 2016.
This comment was minimized by the moderator on the site
I'm looking to give a cell a name based on the colour within one worksheet. i.e. if a cell is red then it gets named "name", if it is orange then it gets names "surname" etc.



What code would need to change to have the range as the whole sheet/tab and a name instead of a value?
This comment was minimized by the moderator on the site
What changes to the code would be needed if you wanted this to apply to the text color of a cell, rather than the cell color?
There are no comments posted here yet
Please leave your comments in English
Posting as Guest
×
Rate this post:
0   Characters
Suggested Locations