Ir para o conteúdo principal

Como classificar várias linhas ou colunas independentemente de uma vez no Excel?

No Excel, você pode aplicar o recurso Classificar para classificar apenas uma linha ou coluna em um intervalo de colunas, mas, se precisar classificar várias linhas ou colunas independentemente de uma vez, para obter a seguinte captura de tela exibida. Existe alguma maneira rápida de resolver essa tarefa no Excel?

doc classificar várias colunas 1

Classifique várias colunas independentemente de uma vez com o código VBA

Classifique várias linhas independentemente de uma vez com o código VBA


seta azul bolha direita Classifique várias colunas independentemente de uma vez com o código VBA

Para classificar várias colunas independentemente em ordem crescente, o seguinte código VBA pode ajudá-lo, faça o seguinte:

1. Segure o ALT + F11 chaves para abrir o Microsoft Visual Basic para Aplicações janela.

2. Clique inserção > Móduloe cole o seguinte código no Módulo Janela.

Código VBA: classifique várias colunas independentemente de uma vez:

Sub SortIndividualJR()
'Updateby Extendoffice
    Dim xRg As Range
    Dim yRg As Range
    Dim ws As Worksheet
    Set ws = ActiveSheet
    On Error Resume Next
    Set xRg = Application.InputBox(Prompt:="Range Selection:", _
                                    Title:="Kutools for excel", Type:=8)
    Application.ScreenUpdating = False
    For Each yRg In xRg
        With ws.Sort
            .SortFields.Clear
            .SortFields.Add Key:=yRg, Order:=xlAscending
            .SetRange ws.Range(yRg, yRg.End(xlDown))
            .Header = xlNo
            .MatchCase = False
            .Apply
        End With
    Next yRg
    Application.ScreenUpdating = True
End Sub

3. Então aperte F5 para executar este código e uma caixa de prompt é exibida para lembrá-lo de selecionar o intervalo de dados que deseja classificar com base em cada coluna, consulte a captura de tela:

doc classificar várias colunas 2

4. E, em seguida, clique em OK, cada coluna foi classificada de forma dependente de uma vez, consulte a captura de tela:

doc classificar várias colunas 1


seta azul bolha direita Classifique várias linhas independentemente de uma vez com o código VBA

Se você deseja classificar várias linhas independentemente, aqui também está um código VBA para você.

1. Selecione os dados que você deseja classificar com base em cada linha.

doc classificar várias colunas 3

2. Segure o ALT + F11 chaves para abrir o Microsoft Visual Basic para Aplicações janela.

3. Clique inserção > Móduloe cole o seguinte código no Módulo Janela.

Código VBA: classifique várias linhas independentemente de uma vez:

Sub SortIndividualR()
'Updateby Extendoffice
    Dim xRg As Range, yRg As Range
    If TypeName(Selection) <> "Range" Then Exit Sub
    Set xRg = Selection
    If xRg.Count = 1 Then
        MsgBox "Select multiple cells!", vbExclamation, "Kutools for Excel"
        Exit Sub
    End If
    With Application
        .ScreenUpdating = False
        .EnableEvents = False
        .Calculation = xlCalculationManual
    End With
    Application.ScreenUpdating = False
    For Each yRg In xRg.Rows
        yRg.Sort Key1:=yRg.Cells(1, 1), _
        Order1:=xlAscending, _
        Header:=xlNo, _
        Orientation:=xlSortRows
    Next yRg
    With Application
        .ScreenUpdating = True
        .EnableEvents = True
        .Calculation = xlCalculationAutomatic
    End With
    Application.ScreenUpdating = True
End Sub

4. Então aperte F5 chave para executar este código, os dados em cada linha foram classificados de uma vez, veja a captura de tela:

doc classificar várias colunas 4

Melhores ferramentas de produtividade de escritório

🤖 Assistente de IA do Kutools: Revolucionar a análise de dados com base em: Execução Inteligente   |  Gerar Código  |  Crie fórmulas personalizadas  |  Analise dados e gere gráficos  |  Invocar funções do Kutools...
Recursos mais comuns: Encontre, destaque ou identifique duplicatas   |  Excluir linhas em branco   |  Combine colunas ou células sem perder dados   |   Rodada sem Fórmula ...
Super pesquisa: VLookup de múltiplos critérios    VLookup de múltiplos valores  |   VLookup em várias planilhas   |   Pesquisa Difusa ....
Lista suspensa avançada: Crie rapidamente uma lista suspensa   |  Lista suspensa de dependentes   |  Lista suspensa de seleção múltipla ....
Gerenciador de colunas: Adicione um número específico de colunas  |  Mover colunas  |  Alternar status de visibilidade de colunas ocultas  |  Compare intervalos e colunas ...
Recursos em destaque: Foco da Grade   |  Vista de Design   |   Grande Barra de Fórmula    Gerenciador de pastas de trabalho e planilhas   |  Biblioteca (Auto texto)   |  Data Picker   |  Combinar planilhas   |  Criptografar/Descriptografar Células    Enviar e-mails por lista   |  Super Filtro   |   Filtro Especial (filtro negrito/itálico/tachado...) ...
15 principais conjuntos de ferramentas12 Texto Ferramentas (Adicionar texto, Remover Personagens, ...)   |   50+ de cores Tipos (Gráfico de Gantt, ...)   |   Mais de 40 práticos Fórmulas (Calcule a idade com base no aniversário, ...)   |   19 Inclusão Ferramentas (Insira o código QR, Inserir imagem do caminho, ...)   |   12 Conversão Ferramentas (Números para Palavras, Conversão de moedas, ...)   |   7 Unir e dividir Ferramentas (Combinar linhas avançadas, Dividir células, ...)   |   ... e mais

Aprimore suas habilidades de Excel com o Kutools para Excel e experimente uma eficiência como nunca antes. Kutools para Excel oferece mais de 300 recursos avançados para aumentar a produtividade e economizar tempo.  Clique aqui para obter o recurso que você mais precisa...

Descrição


Office Tab traz interface com guias para o Office e torna seu trabalho muito mais fácil

  • Habilite a edição e leitura com guias em Word, Excel, PowerPoint, Publisher, Access, Visio e Project.
  • Abra e crie vários documentos em novas guias da mesma janela, em vez de em novas janelas.
  • Aumenta sua produtividade em 50% e reduz centenas de cliques do mouse para você todos os dias!
Comments (11)
No ratings yet. Be the first to rate!
This comment was minimized by the moderator on the site
My data ranges from 0-100; When I Try to sort multiples rows at once, it starts the data off with the 100s, then sorts the rest numerically least to greatest, putting the 100s at the least side of the range. How can I fix this?
This comment was minimized by the moderator on the site
Update; I've realized it is sorting by the first digit in the number only - How do I get it to sort by the whole number?
This comment was minimized by the moderator on the site
Hi, Devyn,
The code works well in my worksheet. Could you upload your Excel file or data screenshot here? So that, we can help to check where the problem is?
Thank you!
This comment was minimized by the moderator on the site
Спасибо тебе человек!!
This comment was minimized by the moderator on the site
excellent post, thank you very much!
This comment was minimized by the moderator on the site
You have just saved me several headaches with this solution! Thanks a ton!
This comment was minimized by the moderator on the site
Thank you so much for this. It really helped. I would also like to know how to sort by color. I have 26 columns, each having different types of items identified by the font color. I would like to alphabetize all the columns individually but in a specific color order. How do I do this?
This comment was minimized by the moderator on the site
I love this, I'm curious as to the functionality of sorting by color for each column individually. I tried this but it didn't work:


Dim xRg As Range
Dim yRg As Range
Dim ws As Worksheet
Set ws = ActiveSheet
On Error Resume Next
Set xRg = Application.InputBox(Prompt:="Range Selection:", _
Title:="Kutools for excel", Type:=8)
Application.ScreenUpdating = False
For Each yRg In xRg
With ws.Sort
.SortFields.Clear
.SortFields.Add Key:=yRg, _
SortOn:=xlSortOnCellColor, Order:=xlDescending, DataOption:=xlSortNormal
.SetRange ws.Range(yRg, yRg.End(xlDown))
.Header = xlNo
.MatchCase = False
.Apply
End With
Next yRg
Application.ScreenUpdating = True
End Sub
This comment was minimized by the moderator on the site
¿Cómo puedo ordenar por color múltiples filas de forma independiente y que las celdas que no tengan color estén a la derecha?
This comment was minimized by the moderator on the site
When I try to sort the columns it sorts data outside of the sected range! Why is this?
This comment was minimized by the moderator on the site
It works great ! thank you !
There are no comments posted here yet
Please leave your comments in English
Posting as Guest
×
Rate this post:
0   Characters
Suggested Locations