Saltar al contenido principal

¿Cómo ordenar los datos de la columna haciendo clic en el encabezado en Excel?

Supongamos que tengo un rango de datos, ahora, me gustaría ordenar los datos en orden ascendente o descendente haciendo clic en el encabezado de cualquier columna para obtener la siguiente captura de pantalla. ¿Cómo podrías resolver este trabajo en Excel?

doc ordenar por clic 1

Ordene los datos haciendo clic en el encabezado de la columna con el código VBA


flecha azul burbuja derecha Ordene los datos haciendo clic en el encabezado de la columna con el código VBA

Normalmente, en Excel, puede aplicar la función Ordenar para ordenar los datos rápida y fácilmente, pero para ordenar los datos simplemente haciendo clic en una celda, el siguiente código VBA puede hacerle un favor.

1. Haga clic con el botón derecho en la pestaña de la hoja en la que desea ordenar los datos haciendo clic en una celda y elija Ver código desde el menú contextual, y en el Microsoft Visual Basic para aplicaciones ventana, copie y pegue el siguiente código en el módulo en blanco:

Código VBA: Ordene los datos haciendo clic en el encabezado de una celda o columna:

Public blnToggle As Boolean
Private Sub Worksheet_BeforeDoubleClick _
(ByVal Target As Range, Cancel As Boolean)
'Updateby Extendoffice
Dim LastColumn As Long, keyColumn As Long, LastRow As Long
Dim SortRange As Range
LastColumn = _
Cells.Find(What:="*", After:=Range("A1"), _
SearchOrder:=xlByColumns, SearchDirection:=xlPrevious).Column
keyColumn = Target.Column
If keyColumn > LastColumn Then Exit Sub
Application.ScreenUpdating = False
Cancel = True
LastRow = Cells(Rows.Count, keyColumn).End(xlUp).Row
Set SortRange = Target.CurrentRegion
blnToggle = Not blnToggle
If blnToggle = True Then
SortRange.Sort _
Key1:=Cells(2, keyColumn), Order1:=xlAscending, Header:=xlYes
Else
SortRange.Sort _
Key1:=Cells(2, keyColumn), Order1:=xlDescending, Header:=xlYes
End If
Set SortRange = Nothing
Application.ScreenUpdating = True
End Sub

doc ordenar por clic 2

2. Y luego guarde y cierre la ventana de código, ahora, cuando haga doble clic en cualquier encabezado de celda o columna dentro del rango de datos, la columna se ordenará en orden ascendente, si hace doble clic en ella nuevamente, la columna se ordenará descendente a la vez.


Más artículos relacionados:

¿Cómo cambiar el valor de la celda haciendo clic en la celda?

¿Cómo filtrar datos con solo hacer clic en el contenido de la celda en Excel?

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 (9)
No ratings yet. Be the first to rate!
This comment was minimized by the moderator on the site
Hallo,
der Code funktioniert auch gut bei mir. Allerdings würde ich gerne die oberen beiden Zeilen nicht mit sortieren, da diese die Überschriften sind.
Wie muss ich dann diesen Code ändern?

Vielen Dank!!
This comment was minimized by the moderator on the site
Hello friend,
Here is the VBA you need:

Public blnToggle As Boolean
Private Sub Worksheet_BeforeDoubleClick _
(ByVal Target As Range, Cancel As Boolean)
'Updateby Extendoffice
Dim LastColumn As Long, keyColumn As Long, LastRow As Long
Dim SortRange As Range
LastColumn = _
Cells.Find(What:="*", After:=Range("A1"), _
SearchOrder:=xlByColumns, SearchDirection:=xlPrevious).Column
keyColumn = Target.Column
If keyColumn > LastColumn Then Exit Sub
Application.ScreenUpdating = False
Cancel = True
LastRow = Cells(Rows.Count, keyColumn).End(xlUp).Row
On Error Resume Next
Set SortRange = Target.CurrentRegion
Dim i As Long
i = 2
Set SortRange = SortRange.Offset(i, 0)
Set SortRange = SortRange.Resize(SortRange.Rows.Count - i, SortRange.Columns.Count)
blnToggle = Not blnToggle
If blnToggle = True Then
SortRange.Sort _
Key1:=Cells(2, keyColumn), Order1:=xlAscending, Header:=xlNo
Else
SortRange.Sort _
Key1:=Cells(2, keyColumn), Order1:=xlDescending, Header:=xlNo
End If
Set SortRange = Nothing
Application.ScreenUpdating = True
End Sub


If you have headers of 3 rows, just change "i =2" to "i =3" in the VBA. Hope it helps. Have a great day.

Sincerely,
Mandy
This comment was minimized by the moderator on the site
Hi Mandy/all,

Is it possible to change your code to only sort when the headers are double clicked instead of any cell?

Thank you very much!
This comment was minimized by the moderator on the site
Hello,
To solve your problem, please apply the below code:
Public blnToggle As Boolean
Private Sub Worksheet_BeforeDoubleClick _
(ByVal Target As Range, Cancel As Boolean)
'Updateby Extendoffice
Dim LastColumn As Long, keyColumn As Long, LastRow As Long
Dim SortRange As Range
Dim xAddress As String
Dim xRgI As Range
xAddress = "A1:E2" 'The headers
Set xRgI = Intersect(Range(xAddress), Target)
If xRgI Is Nothing Then Exit Sub
LastColumn = _
Cells.Find(What:="*", After:=Range("A1"), _
SearchOrder:=xlByColumns, SearchDirection:=xlPrevious).Column
keyColumn = Target.Column
If keyColumn > LastColumn Then Exit Sub
Application.ScreenUpdating = False
Cancel = True
LastRow = Cells(Rows.Count, keyColumn).End(xlUp).Row
On Error Resume Next
Set SortRange = Target.CurrentRegion
Dim i As Long
i = 2
Set SortRange = SortRange.Offset(i, 0)
Set SortRange = SortRange.Resize(SortRange.Rows.Count - i, SortRange.Columns.Count)
blnToggle = Not blnToggle
If blnToggle = True Then
SortRange.Sort _
Key1:=Cells(2, keyColumn), Order1:=xlAscending, Header:=xlNo
Else
SortRange.Sort _
Key1:=Cells(2, keyColumn), Order1:=xlDescending, Header:=xlNo
End If
Set SortRange = Nothing
Application.ScreenUpdating = True
End Sub



Please have a try, hope it can help you!
This comment was minimized by the moderator on the site
This works perfectly! Thank you very much skyyang!
This comment was minimized by the moderator on the site
No can do crackerjack - don't work
This comment was minimized by the moderator on the site
Hi, Rob, The above code works well in my Excel, can you give your problem a screenshot here?
This comment was minimized by the moderator on the site
Doesn't work, nothing happens, know how to create module in vba, did that, saved and nothing when header double clicked. Please fix it.
This comment was minimized by the moderator on the site
Works ok to ascend, double click a 2nd time as stated to descend does nothing
There are no comments posted here yet
Please leave your comments in English
Posting as Guest
×
Rate this post:
0   Characters
Suggested Locations