Saltar al contenido principal
Escrito por: xiaoyang Última modificación: 2023-12-01

Navegar a través de extensas hojas de cálculo de Excel repletas de datos puede ser un desafío y es fácil perder la noción de su posición o leer mal los valores. Para mejorar su análisis de datos y reducir la posibilidad de errores, presentaremos 3 formas diferentes de resaltar dinámicamente la fila y columna de una celda seleccionada en Excel. A medida que pasa de una celda a otra, el resaltado cambia dinámicamente, lo que proporciona una señal visual clara e intuitiva para mantenerlo enfocado en los datos correctos, como se muestra en la siguiente demostración:

Resaltar automáticamente fila y columna activas en Excel


Vídeo: Resaltar automáticamente fila y columna activas en Excel


Resalte automático de fila y columna activas con código VBA

Para resaltar automáticamente toda la columna y fila de la celda seleccionada en la hoja de trabajo actual, el siguiente código VBA puede ayudarle a realizar esta tarea.

Paso 1: abra la hoja de trabajo donde desea resaltar automáticamente la fila y columna activas

Paso 2: abra el editor del módulo de hoja VBA y copie el código

  1. Haga clic derecho en el nombre de la hoja y elija Ver código en el menú contextual, vea la captura de pantalla:
  2. En el editor de módulo de hoja VBA abierto, copie y pegue el siguiente código en el módulo en blanco. Ver captura de pantalla:
    Código de VBA: resaltar automáticamente la fila y la columna de la celda seleccionada
    Private Sub Worksheet_SelectionChange(ByVal Target As Range)
    'Update by Extendoffice
        Dim rowRange As Range
        Dim colRange As Range
        Dim activeCell As Range
        Set activeCell = Target.Cells(1, 1)
        Set rowRange = Rows(activeCell.Row)
        Set colRange = Columns(activeCell.Column)
         Cells.Interior.ColorIndex = xlNone
        rowRange.Interior.Color = RGB(248, 150, 171)
        colRange.Interior.Color = RGB(173, 233, 249)
    End Sub
    
    Consejos: personaliza el código
    • Para cambiar el color de resaltado, simplemente necesita modificar el valor RGB en los siguientes scripts:
      rango de filas.Interior.Color = RGB(248, 150, 171)
      colRange.Interior.Color = RGB(173, 233, 249)
    • Para resaltar solo toda la fila de la celda seleccionada, elimine o comente (agregue un apóstrofo al frente) esta línea:
      colRange.Interior.Color = RGB(173, 233, 249)
    • Para resaltar solo la columna completa de la celda seleccionada, elimine o comente (agregue un apóstrofo al frente) esta línea:
      rango de filas.Interior.Color = RGB(248, 150, 171)

  3. Luego, cierre la ventana del editor de VBA para regresar a la hoja de trabajo.

Resultado:

Ahora, cuando selecciona una celda, toda la fila y columna de esa celda se resaltan automáticamente, y el resaltado cambia dinámicamente a medida que la celda seleccionada cambia como se muestra a continuación:

Notas:
  • Este código borrará los colores de fondo de todas las celdas de la hoja de trabajo, por lo tanto, evite usar esta solución si tiene celdas con colores personalizados.
  • La ejecución de este código desactivará el deshacer característica en la hoja, lo que significa que no puede revertir ningún error presionando el botón Ctrl + Z atajo.
  • Este código no funcionará en una hoja de trabajo protegida.
  • Para dejar de resaltar la fila y la columna de la celda seleccionada, deberá eliminar el código VBA agregado previamente. Después de eso, para restablecer el resaltado haciendo clic Inicio > Color de relleno > Sin relleno.

Resalte automáticamente la fila y columna activas con solo un clic en Kutools

¿Enfrenta las limitaciones del código VBA en Excel? Kutools para Excel's Enfoque de cuadrícula ¡La característica es su solución ideal! Diseñado para abordar las deficiencias de VBA, ofrece una amplia gama de estilos de resaltado para mejorar su experiencia con las hojas. Con su capacidad de aplicar estos estilos en todos los libros abiertos, Kutools garantiza un proceso de gestión de datos consistentemente eficiente y visualmente atractivo.

Note: Si quieres usar esto Enfoque de cuadrícula característica, por favor descargue e instale Kutools para Excel de antemano.

Después de instalar Kutools for Excel, Por favor haga clic en Kutools > Enfoque de cuadrícula para habilitar esta característica. Ahora puede ver que la fila y la columna de la celda activa se resaltan inmediatamente. Este resaltado cambia dinámicamente a medida que cambia su selección de celda. Vea la demostración a continuación:

Beneficios clave de la función Grid Focus:
  • Conserva los colores de fondo originales de la celda:
    A diferencia del código VBA, esta función respeta el formato existente de su hoja de trabajo.
  • Utilizable en hojas protegidas:
    Esta característica funciona perfectamente dentro de hojas de trabajo protegidas, lo que la hace ideal para administrar documentos confidenciales o compartidos sin comprometer la seguridad.
  • No afecta la función Deshacer:
    Con esta función, conserva el acceso completo a la funcionalidad de deshacer de Excel. Esto garantiza que pueda revertir los cambios fácilmente, agregando una capa de seguridad a la manipulación de sus datos.
  • Rendimiento estable con grandes datos:
    Esta función está diseñada para manejar grandes conjuntos de datos de manera eficiente, lo que garantiza un rendimiento estable incluso en hojas de cálculo complejas y con un uso intensivo de datos.
  • Múltiples estilos de resaltado:
    Esta característica ofrece una variedad de opciones de resaltado, lo que le permite elegir entre diferentes estilos y colores para hacer que su celda activa de fila, columna o fila y columna se destaque de la manera que mejor se adapte a sus preferencias y necesidades.
Consejos:
  • Para desactivar esta función, haga clic en Kutools > Enfoque de cuadrícula nuevamente para cerrar esta función;
  • Para aplicar esta función, por favor descargue e instale Kutools para Excel de antemano.

Resalte automático de fila y columna activas con formato condicional

En Excel, también puede configurar el formato condicional para resaltar automáticamente la fila y columna activas. Para configurar esta función, siga estos pasos:

Paso 1: seleccione el rango de datos

Primero, seleccione el rango de celdas al que desea que se aplique esta función. Podría ser la hoja de trabajo completa o un conjunto de datos específico. Aquí seleccionaré toda la hoja de trabajo.

Paso 2: acceda al formato condicional

Haga Clic en Inicio > Formato condicional > Nueva regla, ver captura de pantalla:

Paso 3: configurar las operaciones en la nueva regla de formato

  1. En Nueva regla de formato cuadro de diálogo, elija Use una fórmula para determinar qué celdas formatear del desplegable Seleccione un tipo de regla cuadro de lista.
  2. En Dar formato a los valores donde esta fórmula es verdadera , ingrese una de estas fórmulas; en este ejemplo, aplicaré la tercera fórmula para resaltar la fila y columna activas.
    Para resaltar la fila activa:
    =CELL("row")=ROW()
    Para resaltar la columna activa:
    =CELL("col")=COLUMN()
    Para resaltar la fila y columna activas:
    =OR(CELL("row")=ROW(), CELL("col")= COLUMN())
  3. Luego, haz clic Formato del botón.
  4. En la siguiente Formato de celdas cuadro de diálogo, debajo del Llene pestaña, elija un color para resaltar la fila y columna activas según lo necesite, vea la captura de pantalla:
  5. Luego, haz clic OK > OK para cerrar los diálogos.

Resultado:

Ahora puede ver que toda la columna y fila de la celda A1 se han resaltado a la vez. Para aplicar este resaltado a otra celda, simplemente haga clic en la celda deseada y presione el botón F9 para actualizar la hoja, que luego resaltará toda la columna y fila de la celda recién seleccionada.

Consejos: 
  • De hecho, si bien el enfoque de formato condicional para resaltar en Excel ofrece una solución, no es tan sencillo como usar VBA y Enfoque de cuadrícula característica. Este método requiere un recálculo manual de la hoja (que se logra presionando el botón F9 llave).
    Para permitir el recálculo automático de su hoja de trabajo, puede incorporar un código VBA simple en el módulo de código de su hoja de destino. Esto automatizará el proceso de actualización, asegurando que el resaltado se actualice inmediatamente a medida que selecciona diferentes celdas sin presionar el botón F9 llave. Haga clic derecho en el nombre de la hoja y luego elija Ver código desde el menú contextual. Luego copie y pegue el siguiente código en el módulo de hoja:
    Private Sub Worksheet_SelectionChange(ByVal Target As Range)
      Target.Calculate
    End Sub
    
  • El formato condicional conserva el formato existente que ha aplicado manualmente a su hoja de trabajo.
  • Se sabe que el formato condicional es volátil, especialmente cuando se aplica a conjuntos de datos muy grandes. Su uso extensivo puede potencialmente ralentizar el rendimiento de su libro, afectando la eficiencia del procesamiento de datos y la navegación.
  • La función CELDA sólo está disponible en las versiones de Excel 2007 y posteriores, este método no es compatible con versiones anteriores de Excel.

Comparación de los métodos anteriores

Feature Código VBA Formato condicional Kutools for Excel
Preservar el color de fondo de la celda No
Admite Deshacer No
Estable en grandes conjuntos de datos No No
Utilizable en hojas protegidas. No
Se aplica a todos los libros abiertos. Solo hoja actual Solo hoja actual Todos los libros abiertos
Requiere actualización manual (F9) No No

Con esto concluye nuestra guía sobre cómo resaltar la columna y la fila de una celda seleccionada en Excel. Si está interesado en explorar más consejos y trucos de Excel, nuestro sitio web ofrece miles de tutoriales, por favor haga clic aquí para acceder a ellos. ¡Gracias por leer y esperamos brindarle más información útil en el futuro!


Artículos relacionados:

  • Resaltar automáticamente la fila y la columna de la celda activa
  • Cuando vea una hoja de trabajo grande con numerosos datos, es posible que desee resaltar la fila y columna de la celda seleccionada para que pueda leer los datos de manera fácil e intuitiva para evitar leerlos mal. Aquí, puedo presentarles algunos trucos interesantes para resaltar la fila y la columna de la celda actual, cuando se cambia la celda, la columna y la fila de la nueva celda se resaltan automáticamente.
  • Resalte cada dos filas o columnas en Excel
  • En una hoja de trabajo grande, resaltar o completar una fila o columna cada dos o cada enésima mejora la visibilidad y legibilidad de los datos. No sólo hace que la hoja de trabajo se vea más ordenada, sino que también le ayuda a comprender los datos más rápidamente. En este artículo, lo guiaremos a través de varios métodos para sombrear cada dos o enésima fila o columna, ayudándole a presentar sus datos de una manera más atractiva y sencilla.
  • Resalte toda la fila mientras se desplaza
  • Si tiene una hoja de trabajo grande con varias columnas, le resultará difícil distinguir los datos en esa fila. En este caso, puede resaltar toda la fila de celda activa para que pueda ver rápida y fácilmente los datos en esa fila cuando se desplaza hacia abajo en la barra de desplazamiento horizontal. En este artículo, hablaré sobre algunos trucos para que pueda resolver este problema .
  • Resaltar filas según la lista desplegable
  • Este artículo hablará sobre cómo resaltar filas según la lista desplegable, tome la siguiente captura de pantalla, por ejemplo, cuando selecciono "En progreso" de la lista desplegable en la columna E, necesito resaltar esta fila con color rojo, cuando seleccione "Completado" de la lista desplegable, necesito resaltar esta fila con color azul, y cuando seleccione "No iniciado", se utilizará un color verde para resaltar la fila.
Comments (61)
Rated 5 out of 5 · 1 ratings
This comment was minimized by the moderator on the site
And please reply to an email
This comment was minimized by the moderator on the site
Great job . But in the first task at the top of the browser page, when I did it, it was working correctly, but when I made protection for the sheet, it stopped working correctly, you see, what's the solution. Thank you
This comment was minimized by the moderator on the site
Hello,
To solve your problem, please apply the followign code:
Private Sub Worksheet_SelectionChange(ByVal Target As Range)
    Dim rowRange As Range
    Dim colRange As Range
    Dim activeCell As Range
    Me.Unprotect
    Cells.Interior.ColorIndex = xlNone
    Set activeCell = Target.Cells(1, 1)
    Set rowRange = Rows(activeCell.Row)
    Set colRange = Columns(activeCell.Column)
    rowRange.Interior.Color = RGB(173, 233, 249)
    colRange.Interior.Color = RGB(173, 233, 249)
    Me.Protect
End Sub



Please have a try, hope it can help you!
This comment was minimized by the moderator on the site
Private Sub Worksheet_SelectionChange(ByVal Target As Range)
    On Error Resume Next
    
    ' Clear previous highlighting
    Me.Cells.FormatConditions.Delete
    
    ' Check if Checkbox1 is checked
    ' If CheckBox1.Value = True Then
        ' Check if a single cell or a range of cells is selected
        If Target.Cells.Count = 1 Or Target.Cells.Count > 1 Then
            Dim selectedRange As Range
            Dim selectedRows As Range
            Dim selectedColumns As Range
            
            Set selectedRange = Target
            Set selectedRows = Me.Range(Me.Cells(selectedRange.Row, 1), Me.Cells(selectedRange.Row + selectedRange.Rows.Count - 1, 1).EntireRow)
            Set selectedColumns = Me.Range(Me.Cells(1, selectedRange.Column), Me.Cells(1, selectedRange.Column + selectedRange.Columns.Count - 1).EntireColumn)
            
            ' Add conditional formatting to highlight the selected rows
            With selectedRows.FormatConditions.Add(Type:=xlExpression, Formula1:="=TRUE")
                .Interior.Color = RGB(255, 230, 153) ' Yellow color
            End With
            
            ' Add conditional formatting to highlight the selected columns
            With selectedColumns.FormatConditions.Add(Type:=xlExpression, Formula1:="=TRUE")
                .Interior.Color = RGB(255, 230, 153) ' Yellow color
            End With
        End If
    ' End If
    
    On Error GoTo 0
End Sub
This comment was minimized by the moderator on the site
Private Sub Worksheet_SelectionChange(ByVal Target As Range)
On Error Resume Next

' Clear previous highlighting
Me.Cells.FormatConditions.Delete

' Check if a single cell or a range of cells is selected
If Target.Cells.Count = 1 Or Target.Cells.Count > 1 Then
Dim selectedRange As Range
Dim selectedRows As Range
Dim selectedColumns As Range

Set selectedRange = Target
Set selectedRows = Me.Range(Me.Cells(selectedRange.Row, 1), Me.Cells(selectedRange.Row + selectedRange.Rows.Count - 1, 1).EntireRow)
Set selectedColumns = Me.Range(Me.Cells(1, selectedRange.Column), Me.Cells(1, selectedRange.Column + selectedRange.Columns.Count - 1).EntireColumn)

' Add conditional formatting to highlight the selected rows
With selectedRows.FormatConditions.Add(Type:=xlExpression, Formula1:="=TRUE")
.Interior.Color = RGB(255, 230, 153) ' Yellow color
End With

' Add conditional formatting to highlight the selected columns
With selectedColumns.FormatConditions.Add(Type:=xlExpression, Formula1:="=TRUE")
.Interior.Color = RGB(255, 230, 153) ' Yellow color
End With
End If

On Error GoTo 0
End Sub
This comment was minimized by the moderator on the site
can you please post code in VBA format? trying to figure out what your code looks like from what you posted in a jumble is frustrating.
This comment was minimized by the moderator on the site
Hi,

The above code is brilliant. But i have two questions and if you can help then will be much appreciated. Let me know if there is cost associated with it.

1. The above code is removing my previous formatting of the cells. Eg. if i have got the cells filld with blue then above code clears that fill.
2. Is there a code that i can use when i am extracting values from another sheet and that row in the that sheet gets highlighted as well. Eg. I want to extract vale from another cell, so when i press = sign in sheet 1 and then when i move to sheet 2 to bring the value the row in the sheet doesn't get highlighted.

Regards,
This comment was minimized by the moderator on the site
Hello, Patel
For the first question:
It may be difficult to modify the VBA code, so, I recommend you to apply the Conditional Formatting feature for solving this problem, the following article may help you:
https://www.extendoffice.com/documents/excel/3500-excel-highlight-selected-row-conditional-formatting.html

Or you can use the Kutools for Excel' Reading Layout feature, you can try it 30 days for free.
Please download from: https://www.extendoffice.com/download/kutools-for-excel.html

For the second question:
Sorry, I can't solve this problem at present,😜
This comment was minimized by the moderator on the site
How do you modify the code so that:
1. It does not permanently strip existing colors of cells. Currently, after another cell is selected, it leaves colorless previous row. I'd like to keep the colors of the worksheet, as they were before row was highlighted by this code.
2. Limit the highlight width to only Columns A thru K, not the entire row.
This comment was minimized by the moderator on the site
Hello,
It may be difficult to modify the VBA code, so, here, I recommend you to apply the Conditional Formatting feature for solving this problem, please view the below article: (Note: if you need to highlight the column A to column K, you just need to select the range you need, and then apply the conditional formatting.)
https://www.extendoffice.com/documents/excel/3500-excel-highlight-selected-row-conditional-formatting.html


Or you can use the Kutools for Excel' Reading Layout feature, you can try it 30 days for free.
Please download from: https://www.extendoffice.com/download/kutools-for-excel.html

Please try, hope it can help you!
This comment was minimized by the moderator on the site
Thank you so much for this tip!!!
Rated 5 out of 5
This comment was minimized by the moderator on the site
Another easy way to highlight your rows: https://youtu.be/iOF06mZDGIk
This comment was minimized by the moderator on the site
FAIL. Wiped out all my other cell formatting irreversibly. And doesn't work if the sheet is protected. FAIL.
This comment was minimized by the moderator on the site
Hi Gues,The code does not work in a protected worksheet. If you want to keep the original cell formatting, please try the below code.The Reading Layout feature of Kutools is stable and handy, maybe you can download a free trial to have a try.
<div data-tag="code">Sub Worksheet_SelectionChange(ByVal Target As Excel.Range)
'Update 202001106
Static xRow
Static xColumn

Dim xWs As Worksheet
Dim xCRg, xCRg1, xRRg, xRRg1, xOHRg As Range
Dim xAHRORg, xAHRORg1 As Range
Dim xAWs As Worksheet
Dim xFNum As Integer
Dim xCll As Range

On Error Resume Next

Application.ScreenUpdating = False
pRow = Selection.Row
pColumn = Selection.Column

Set xWs = ActiveWorkbook.Worksheets.Item("AutoHighlightRAndC")
Set xAWs = Target.Worksheet
If xWs Is Nothing Then
Set xWs = ActiveWorkbook.Worksheets.Add
xWs.Name = "AutoHighlightRAndC"
xWs.Visible = xlSheetHidden
xAWs.Activate
End If

If xColumn <> "" Then
Set xCRg = Columns(xColumn)
xCRg.Interior.ColorIndex = xlNone
Set xCRg = Intersect(xCRg.Worksheet.UsedRange, xCRg)
For xFNum = 1 To xCRg.Count
Set xAHRORg1 = xAWs.Cells(xFNum, xColumn)
Set xAHRORg = xWs.Cells(xFNum, xColumn)
xAHRORg1.Interior.ColorIndex = xAHRORg.Interior.ColorIndex
'xCRg.Item(xFNum).Interior.ColorIndex = xWs.Columns(xColumn).Item(xFNum).Interior.ColorIndex
Next

Set xRRg = Rows(xRow)
xRRg.Interior.ColorIndex = xlNone
Set xRRg = Intersect(xCRg.Worksheet.UsedRange, xCRg)
For xFNum = 1 To xRRg.Count
Set xAHRORg1 = xAWs.Cells(xRow, xFNum)
Set xAHRORg = xWs.Cells(xRow, xFNum)
xAHRORg1.Interior.ColorIndex = xAHRORg.Interior.ColorIndex
'xRRg.Item(xFNum).Interior.ColorIndex = xWs.Rows(xRow).Item(xFNum).Interior.ColorIndex
Next

End If

xRow = pRow
xColumn = pColumn

Set xCRg = Columns(pColumn)
Set xCRg1 = Intersect(xCRg.Worksheet.UsedRange, xCRg)
For xFNum = 1 To xCRg1.Count
Set xOHRg = xWs.Cells(xFNum, pColumn)
xOHRg.Interior.ColorIndex = xCRg1.Item(xFNum).Interior.ColorIndex
Next

Set xRRg = Rows(pRow)
Set xRRg1 = Intersect(xRRg.Worksheet.UsedRange, xRRg)

For xFNum = 1 To xRRg1.Count
Set xCll = xWs.Cells(pRow, xFNum)
xCll.Interior.ColorIndex = xRRg1.Item(xFNum).Interior.ColorIndex
Next
xCRg.Interior.ColorIndex = 34
xRRg.Interior.ColorIndex = 34
Application.ScreenUpdating = True
End Sub
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