Saltar al contenido principal

¿Cómo dividir una tabla grande en varias tablas pequeñas en Excel?

Si tiene una hoja de trabajo grande que contiene varias columnas y cientos o miles de datos de filas, ahora, desea dividir esta tabla grande en varias tablas pequeñas según el valor de la columna o el número de filas para obtener los siguientes resultados. ¿Cómo podría hacer frente a esta tarea en Excel?

Mesa principal   Dividir la tabla en varias tablas por valor de columna Dividir la tabla en varias tablas por recuento de filas

Divida una tabla grande en varias tablas según el valor de la columna con código VBA

Divida una tabla grande en varias tablas según el número específico de filas con código VBA

Divida una tabla grande en varias tablas según el valor de la columna o el número de filas con una característica sorprendente


Divida una tabla grande en varias tablas según el valor de la columna con código VBA

Para dividir esta tabla grande en varias tablas en función de un valor de columna específico, el siguiente código de VBA puede hacerle un favor. Por favor haz lo siguiente:

1. Mantenga pulsado el ALT + F11 teclas para abrir el Microsoft Visual Basic para aplicaciones ventana.

2. Hacer clic recuadro > Móduloy pegue el siguiente código en el Módulo Ventana.

Código de VBA: divida una tabla grande en varias tablas por columna clave:

Sub Splitdatabycol()
'by Extendoffice
Dim lr As Long
Dim ws As Worksheet
Dim vcol, i As Integer
Dim icol As Long
Dim myarr As Variant
Dim title As String
Dim titlerow As Integer
Dim xTRg As Range
Dim xVRg As Range
Dim xWSTRg As Worksheet
On Error Resume Next
Set xTRg = Application.InputBox("Please select the header rows:", "Kutools for Excel", "", Type:=8)
If TypeName(xTRg) = "Nothing" Then Exit Sub
Set xVRg = Application.InputBox("Please select the column you want to split data based on:", "Kutools for Excel", "", Type:=8)
If TypeName(xVRg) = "Nothing" Then Exit Sub
vcol = xVRg.Column
Set ws = xTRg.Worksheet
lr = ws.Cells(ws.Rows.Count, vcol).End(xlUp).Row
title = xTRg.AddressLocal
titlerow = xTRg.Cells(1).Row
icol = ws.Columns.Count
ws.Cells(1, icol) = "Unique"
Application.DisplayAlerts = False
If Not Evaluate("=ISREF('xTRgWs_Sheet!A1')") Then
Sheets.Add(after:=Worksheets(Worksheets.Count)).Name = "xTRgWs_Sheet"
Else
Sheets("xTRgWs_Sheet").Delete
Sheets.Add(after:=Worksheets(Worksheets.Count)).Name = "xTRgWs_Sheet"
End If
Set xWSTRg = Sheets("xTRgWs_Sheet")
xTRg.Copy
xWSTRg.Paste Destination:=xWSTRg.Range("A1")
ws.Activate
For i = (titlerow + xTRg.Rows.Count) To lr
On Error Resume Next
If ws.Cells(i, vcol) <> "" And Application.WorksheetFunction.Match(ws.Cells(i, vcol), ws.Columns(icol), 0) = 0 Then
ws.Cells(ws.Rows.Count, icol).End(xlUp).Offset(1) = ws.Cells(i, vcol)
End If
Next
myarr = Application.WorksheetFunction.Transpose(ws.Columns(icol).SpecialCells(xlCellTypeConstants))
ws.Columns(icol).Clear
For i = 2 To UBound(myarr)
ws.Range(title).AutoFilter field:=vcol, Criteria1:=myarr(i) & ""
If Not Evaluate("=ISREF('" & myarr(i) & "'!A1)") Then
Sheets.Add(after:=Worksheets(Worksheets.Count)).Name = myarr(i) & ""
Else
Sheets(myarr(i) & "").Move after:=Worksheets(Worksheets.Count)
End If
xWSTRg.Range(title).Copy
Sheets(myarr(i) & "").Paste Destination:=Sheets(myarr(i) & "").Range("A1")
ws.Range("A" & (titlerow + xTRg.Rows.Count) & ":A" & lr).EntireRow.Copy Sheets(myarr(i) & "").Range("A" & (titlerow + xTRg.Rows.Count))
Sheets(myarr(i) & "").Columns.AutoFit
Next
xWSTRg.Delete
ws.AutoFilterMode = False
ws.Activate
Application.DisplayAlerts = True
End Sub

3. Después de pegar el código, presione F5 clave para ejecutar este código, y aparece un cuadro emergente, seleccione la fila de encabezado de sus datos, vea la captura de pantalla:

4. Luego, haz clic OK, y aparece otro cuadro de diálogo, seleccione los datos de la columna en los que desea dividir la tabla, vea la captura de pantalla:

5. Hacer clic OK, esta gran tabla se ha dividido en varias hojas de trabajo por el valor de la columna que se encuentra después de la hoja maestra. Y las nuevas hojas de trabajo se nombran con el valor de la columna. Ver captura de pantalla:


Divida una tabla grande en varias tablas según el número específico de filas con código VBA

Si necesita dividir la tabla en varias tablas según la cantidad de filas, el siguiente código VBA puede ayudarlo.

1. Mantenga pulsado el ALT + F11 teclas para abrir el Microsoft Visual Basic para aplicaciones ventana.

2. Hacer clic recuadro > Móduloy pegue el siguiente código en el Módulo Ventana.

Código de VBA: divida una tabla grande en varias tablas por número de filas:

Sub Splitdatabyrows()
'Updated by Extendoffice 
Dim WorkRng As Range
Dim xRow As Range
Dim SplitRow As Integer
Dim xWs As Worksheet
Dim xTRg As Range
Dim xNTRg As Range
Dim xIER
On Error Resume Next
xTitleId = "KutoolsforExcel"
Set WorkRng = Application.Selection
Set xTRg = Application.InputBox("Please select the header row:", xTitleId, "", Type:=8)
If TypeName(xTRg) = "Nothing" Then Exit Sub
Set WorkRng = Application.InputBox("Please select the data range(exclude the header row):", xTitleId, WorkRng.Address, Type:=8)
If TypeName(WorkRng) = "Nothing" Then Exit Sub
SplitRow = Application.InputBox("Split Row Num", xTitleId, Type:=1)
If SplitRow = 0 Then Exit Sub
Set xWs = WorkRng.Parent
Set xRow = WorkRng.Rows(1)
xIER = WorkRng.Rows.Count
xIER = WorkRng.Row + xIER - 1
Application.ScreenUpdating = False
For i = 1 To WorkRng.Rows.Count Step SplitRow
    resizeCount = SplitRow
    If (xIER - xRow.Row + 1) < SplitRow Then
        resizeCount = (xIER - xRow.Row + 1)
    End If
    xRow.Resize(resizeCount).Copy
    Set xWs = Application.Worksheets.Add(after:=Application.Worksheets(Application.Worksheets.Count))
    If xIER > (xRow.Row + SplitRow - 1) Then
        xWs.Name = xRow.Row & " - " & (xRow.Row + SplitRow - 1)
    ElseIf xIER = xRow.Row Then
        xWs.Name = xRow.Row
    Else
        xWs.Name = xRow.Row & " - " & xIER
    End If
    Application.ActiveSheet.Range("A1").PasteSpecial
    Set xNTRg = Application.ActiveSheet.Range("A1")
    xTRg.Copy
    xNTRg.Insert
    Set xRow = xRow.Offset(SplitRow)
Next
Application.CutCopyMode = False
Application.ScreenUpdating = True
End Sub

3. Entonces presione F5 clave, en el cuadro de diálogo emergente, seleccione la fila del encabezado, vea la captura de pantalla:

4. Luego, haz clic OK, y en el segundo cuadro de solicitud, seleccione el rango de datos que desea dividir por recuento de filas, vea la captura de pantalla:

5. Y luego, sigue haciendo clic OK , en el tercer cuadro de solicitud, ingrese el número de filas por las que desea dividir, vea la captura de pantalla:

6. Luego, haz clic OK , la tabla maestra se ha dividido en varias hojas de trabajo en función del número de filas como se muestra a continuación:


Divida una tabla grande en varias tablas según el valor de la columna o el número de filas con una característica sorprendente

Puede ser que los códigos anteriores sean difíciles para la mayoría de los usuarios, aquí, presentaré una característica sorprendente:Dividir datos of Kutools for Excel. Con esta utilidad, puede dividir una tabla grande en varias tablas por columna clave o número de filas de forma rápida y sencilla.

Consejos:Para aplicar esto Dividir datos función, en primer lugar, debe descargar la Kutools for Excely, a continuación, aplique la función de forma rápida y sencilla.

Después de instalar Kutools for Excel, haz lo siguiente:

1. Seleccione el rango de datos que desea dividir y luego haga clic en Kutools Más > Dividir datos, ver captura de pantalla:

2. En la Dividir datos en varias hojas de trabajo cuadro de diálogo, especifique la configuración a su necesidad:

(1.) Seleccione Columna específica or Filas fijas del desplegable Dividir basado en sección que necesite;

(2.) Especifique el nombre de la nueva hoja de trabajo del Reglas lista desplegable, puede agregar el Prefijo or Sufijo a los nombres de las hojas también.

3. Luego, haz clic Ok y ahora, la tabla grande se ha dividido en varias tablas pequeñas en un nuevo libro de trabajo. Ver capturas de pantalla:

Dividir la tabla en varias tablas por valor de columna Dividir la tabla en varias tablas por recuento de filas

¡Haga clic para descargar Kutools para Excel y prueba gratuita ahora!


Artículos más relativos:

  • Dividir un libro de trabajo para separar archivos de Excel en Excel
  • Es posible que deba dividir un libro grande para separar los archivos de Excel y guardar cada hoja de trabajo del libro como un archivo de Excel individual. Por ejemplo, puede dividir un libro en varios archivos de Excel individuales y luego entregar cada archivo a una persona diferente para que lo maneje. Al hacerlo, puede lograr que ciertas personas manejen datos específicos y mantengan sus datos seguros. Este artículo presentará formas de dividir un libro grande para separar archivos de Excel según cada hoja de trabajo.
  • Dividir el nombre completo en nombre y apellido en Excel
  • Supongamos que tiene una lista de nombres como se muestra en la primera captura de pantalla en una sola columna a continuación, y necesita dividir el nombre completo en la columna del nombre, la columna del segundo nombre y la columna del apellido como se muestra en la siguiente captura de pantalla. Aquí hay algunos métodos complicados para ayudarlo a resolver este problema.
  • Dividir palabra o número en celdas separadas en Excel
  • Si tiene una lista de números o palabras en una hoja de trabajo, y ahora necesita dividir el contenido de la celda en letras en diferentes celdas como se muestra en la siguiente captura de pantalla, ¿cómo puede lidiar con este trabajo en Excel?

 


  • Barra de súper fórmula (edite fácilmente varias líneas de texto y fórmulas); Diseño de lectura (leer y editar fácilmente un gran número de celdas); Pegar en rango filtrado...
  • Combinar celdas / filas / columnas y conservación de datos; Contenido de celdas divididas; Combinar filas duplicadas y suma / promedio... Prevenir celdas duplicadas; Comparar rangos...
  • Seleccione Duplicado o Único Filas; Seleccionar filas en blanco (todas las celdas están vacías); Super Find y Fuzzy Find en muchos libros de trabajo; Selección aleatoria ...
  • Copia exacta Varias celdas sin cambiar la referencia de la fórmula; Crear referencias automáticamente a varias hojas; Insertar viñetas, Casillas de verificación y más ...
  • Fórmulas favoritas e insertar rápidamente, Rangos, gráficos e imágenes; Cifrar celdas con contraseña; Crear lista de distribución y enviar correos electrónicos ...
  • Extraer texto, Agregar texto, Eliminar por posición, Quitar espacio; Crear e imprimir subtotales de paginación; Convertir entre contenido de celdas y comentarios...
  • Súper filtro (guardar y aplicar esquemas de filtros a otras hojas); Orden avanzado por mes / semana / día, frecuencia y más; Filtro especial en negrita, cursiva ...
  • Combinar libros y hojas de trabajo; Combinar tablas basadas en columnas clave; Dividir datos en varias hojas; Conversión por lotes de xls, xlsx y PDF...
  • Agrupación de tablas dinámicas por número de semana, día de la semana y más ... Mostrar celdas bloqueadas y desbloqueadas por diferentes colores; Resalte las celdas que tienen fórmula / nombre...
pestaña kte 201905
  • 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!
officetab parte inferior

 

Comments (13)
No ratings yet. Be the first to rate!
This comment was minimized by the moderator on the site
Thank you very much.....
This comment was minimized by the moderator on the site
Super Sache

Frage:

Ist es möglich die Tabelle immer neu zu füllen und neu zu berechnen.
Bin absoluter anfänger. :-)
Danke im Voraus
This comment was minimized by the moderator on the site
Hello, Lukas,
I'm sorry, the methods in this article can't support to update the new data when the original data is changed.
So, you need to run the code again to get the latest data if there are changes in your data.
Thank you!
This comment was minimized by the moderator on the site
I can't get this macro to work (Split A Large Table Into Multiple Tables Based On Column Value With VBA Code)
My table has 5 columns and 639,165 rows. Is it too big?
This comment was minimized by the moderator on the site
Hello, Rebekah

If the data is too large, the code will not work perfectly.
Here, I recommend our Kutools for Excel' Split Data feature for you. With this feature, you can split large data to multiple sheets quickly and easily.
You can try it for 30 days freely. Please download it ffrom: https://www.extendoffice.com/download/kutools-for-excel.html
Please have a try, hope it can help you!
This comment was minimized by the moderator on the site
Hallo zusammen. Ich habe das gleiche Problem wie cGast - gibt es dazu eine Lösung?
This comment was minimized by the moderator on the site
Hi, Miriam,

The VBA code has been updated to a new one in this article, please try it again, if you have any other problem, please comment here. Thank you!
This comment was minimized by the moderator on the site
I tried "Split a large table into multiple tables based on the specific number of rows with VBA code" with my data of 103,000 rows split in groups of 15000 which should have returned 8 sheets, however it didnt work, it just produced 8 sheets with the headers only. but it does work when i use it with less that 10000rows. any help there?
This comment was minimized by the moderator on the site
Hello cguest,
Yes, as you said, the VBA code does not work correctlly when there are lots of data, here, I provide a new code, please try:
Sub Splitdatabyrows()
'Updated by Extendoffice 
Dim WorkRng As Range
Dim xRow As Range
Dim SplitRow As Integer
Dim xWs As Worksheet
Dim xTRg As Range
Dim xNTRg As Range
Dim xIER
On Error Resume Next
xTitleId = "KutoolsforExcel"
Set WorkRng = Application.Selection


Set xTRg = Application.InputBox("Please select the header row:", xTitleId, "", Type:=8)
If TypeName(xTRg) = "Nothing" Then Exit Sub
Set WorkRng = Application.InputBox("Please select the data range(exclude the header row):", xTitleId, WorkRng.Address, Type:=8)
If TypeName(WorkRng) = "Nothing" Then Exit Sub


SplitRow = Application.InputBox("Split Row Num", xTitleId, Type:=1)
If SplitRow = 0 Then Exit Sub

Set xWs = WorkRng.Parent
Set xRow = WorkRng.Rows(1)
xIER = WorkRng.Rows.Count
xIER = WorkRng.Row + xIER - 1


Application.ScreenUpdating = False
For i = 1 To WorkRng.Rows.Count Step SplitRow
    resizeCount = SplitRow
    If (xIER - xRow.Row + 1) < SplitRow Then
        resizeCount = (xIER - xRow.Row + 1)
    End If
    xRow.Resize(resizeCount).Copy
    Set xWs = Application.Worksheets.Add(after:=Application.Worksheets(Application.Worksheets.Count))
    If xIER > (xRow.Row + SplitRow - 1) Then
        xWs.Name = xRow.Row & " - " & (xRow.Row + SplitRow - 1)
    ElseIf xIER = xRow.Row Then
        xWs.Name = xRow.Row
    Else
        xWs.Name = xRow.Row & " - " & xIER
    End If
    Application.ActiveSheet.Range("A1").PasteSpecial
    Set xNTRg = Application.ActiveSheet.Range("A1")
    xTRg.Copy
    xNTRg.Insert
    Set xRow = xRow.Offset(SplitRow)
Next
Application.CutCopyMode = False
Application.ScreenUpdating = True
End Sub


Hope it can help you, Thank you!
This comment was minimized by the moderator on the site
"Teilen Sie eine große Tabelle basierend auf der spezifischen Anzahl von Zeilen mit VBA-Code in mehrere Tabellen auf"Funktioniert echt Super. Ist es möglich dass auch Verbundene Zellen erkannt und die Anzahl der Zeilen entsprechend angepasst wird so dass die Verbundenen Zellen beim Seitenumbruch nicht getrennt werden?
This comment was minimized by the moderator on the site
Если разбиваете по строкам и строк больше, чем 32 767 то поменяйте тип данных у переменных xIER и SplitRow с Integer на Long
This comment was minimized by the moderator on the site
Ich habe die erste Variante mit 456.913 Zeilen und 8 Spalten probiert - leider ohne dass irgendwas ausgeführt wurde.
This comment was minimized by the moderator on the site
Всем привет. Столкнулся с проблемой. У меня таблица из 7 колонок и 235000 строк. Макрос не разбивает на страницы. Вернее он страницы создает но они внутри пустые. Тестировал с меньшим количеством строк примерно 1000. Макрос срабатывал. Подскажите метод решения.
There are no comments posted here yet
Please leave your comments in English
Posting as Guest
×
Rate this post:
0   Characters
Suggested Locations