Para Dante - Ayuda con esta Macro

Hola Dante:

¿

Podrías ayudarme con esta macro?

Lo que pasa es que grave esta macho pero es muy lenta en su ejecución y quisiera hacerla más rápida. Esta es la macro:

Private Sub CommandButton1_Click()

Application.ScreenUpdating = False
Application.Calculation = xlCalculationManual
Application.EnableEvents = False
ActiveSheet.DisplayPageBreaks = False

Dim Periodo As Integer 'Declaramos la variable
Sheets("LVIVA").Activate 'Activamos la Hoja
Periodo = txtPeriodo.Value 'Asignamos a textbox el valor de la variable
Cells(2, 21) = Periodo 'coordenadas el valor de la variable Periodo dentro de la hoja de excel activa

'Filtramos los datos
Sheets("LVI").Range("A1:S10001").AdvancedFilter Action:=xlFilterCopy, _
CriteriaRange:=Range("LVIVA!LVIVACriterios"), CopyToRange:=Range("A4:S1500" _
), Unique:=False
'Ordenamos los datos primero por numero de documento, fecha y numero de control
Range("A4").Select
Range(Selection, Selection.End(xlToRight)).Select
Range(Selection, Selection.End(xlDown)).Select
ActiveWorkbook.Worksheets("LVIVA").Sort.SortFields.Clear
ActiveWorkbook.Worksheets("LVIVA").Sort.SortFields.Add Key:=Range("E5:E1500"), _
SortOn:=xlSortOnValues, Order:=xlAscending, DataOption:=xlSortNormal
ActiveWorkbook.Worksheets("LVIVA").Sort.SortFields.Add Key:=Range("C5:C1500"), _
SortOn:=xlSortOnValues, Order:=xlAscending, DataOption:=xlSortNormal
ActiveWorkbook.Worksheets("LVIVA").Sort.SortFields.Add Key:=Range("D5:D1500"), _
SortOn:=xlSortOnValues, Order:=xlAscending, DataOption:=xlSortNormal
With ActiveWorkbook.Worksheets("LVIVA").Sort
.SetRange Range("A4:S1500")
.Header = xlYes
.MatchCase = False
.Orientation = xlTopToBottom
.SortMethod = xlPinYin
.Apply
End With
'Númeramos las filas y copiamos el archivo a la hoja LVTXT
Range("B5").Select
ActiveCell.FormulaR1C1 = "1"
Range("B6").Select
ActiveCell.FormulaR1C1 = "=IF(RC[-1]=3,R[-1]C+1,"""")"
Range("B6").Select
Selection.Copy
Range("A6").Select
Selection.End(xlDown).Select
Range("B1500").Select
Range(Selection, Selection.End(xlUp)).Select
ActiveSheet.Paste
Application.CutCopyMode = False
Sheets("LVTXT").Select
Cells.Select
Selection.ClearContents
Sheets("LVIVA").Select
Range("A5").Select
Range(Selection, Selection.End(xlToRight)).Select
Range(Selection, Selection.End(xlDown)).Select
Selection.Copy
Sheets("LVTXT").Select
Range("A1").Select
ActiveSheet.Paste
Application.CutCopyMode = False
Columns("R:S").Select
Range("S1").Activate
Selection.ClearContents
ActiveWorkbook.Save
'Configuramos 17 columnas en el listbox1
ListBox1.ColumnCount = 17
ListBox1.TextAlign = fmTextAlignRight
ListBox1.ColumnHeads = False
ListBox1.ColumnWidths = "25;15;60;40;60;20;60;160;60;60;60;60;60;60;60;60;60"

'Llenamos la lista
ListBox1.RowSource = "LVTXT!A1:Q" & Sheets("LVTXT").Range("A" & Rows.Count).End(xlUp).Row

'Configuramos 8 columnas en el listbox2 PARA LOS TOTALES
ListBox2.ColumnCount = 8
ListBox2.TextAlign = fmTextAlignRight
ListBox2.ColumnHeads = False
ListBox2.ColumnWidths = "60;60;60;60;60;60;60;60"

'Llenamos la lista
ListBox2.RowSource = "LVIVA!Z2:AG" & Sheets("LVIVA").Range("Z" & Rows.Count).End(xlUp).Row


Application.ScreenUpdating = True
Application.Calculation = xlCalculationAutomatic
Application.EnableEvents = True
ActiveSheet.DisplayPageBreaks = True
Application.CutCopyMode = False

End Sub

Lo que hace: primero aciva la Hoja LVIVA luego hace un filtro avanzado después ordena los datos filtrados por numero de documento, fecha y numero de control luego en la Columna Nº numero los registro filtrados ( es decir si el filtro arroja 14 filas se numera de 1 a 14).

Gracias por tu ayuda

1 respuesta

Respuesta
1

¿Dime cuánto tiempo tarda en la ejecución?

Envíame tu archivo con el formulario, me dices cómo se llama el formulario y qué datos debo poner en el formulario antes de ejecutarlo.

Recuerda poner tu nombre en el asunto del correo.

Reviso la forma de optimizarlo y te envío una propuesta.

Saludos. Dante Amor

hab_ra_ham

Ten envio el archivo

https://mega.co.nz/#!YZYXCICb!DQBa-swGiwyvAeVW6naPhbdCP904lI-yLjQXlh12BvY 

tarda como 5 seg.

Los datos se ingresan en la hoja lvt 

para ejecutarlo solo se selecciona el mes y dar click a procesar

Te anexo el código con los cambios, pero creo que lo más significativo es que no guardes el libro cada vez que ejecutas el filtro.

Private Sub CommandButton1_Click()
'Act.Por Dante Amor
    Application.ScreenUpdating = False
    Set h1 = Sheets("LVIVA")
    Set h2 = Sheets("LVI")
    Set h3 = Sheets("LVTXT")
    h3.Cells.ClearContents
    h1.Columns("A:S").ClearContents
    h1.Cells(2, 21) = Val(txtPeriodo.Value)
    u2 = h2.Range("A" & Rows.Count).End(xlUp).Row
    'Filtramos los datos
    h2.Range("A1:S" & u2).AdvancedFilter _
        Action:=xlFilterCopy, _
        CriteriaRange:=Range("LVIVA!LVIVACriterios"), _
        CopyToRange:=h1.Range("A4"), Unique:=False
    'Ordenamos los datos primero por numero de documento, fecha y numero de control
    u1 = h1.Range("A" & Rows.Count).End(xlUp).Row
    If u1 > 4 Then
        With h1.Sort
            .SortFields.Clear
            .SortFields.Add Key:=Range("E5:E" & u1)
            .SortFields.Add Key:=Range("C5:C" & u1)
            .SortFields.Add Key:=Range("D5:D" & u1)
            .SetRange h1.Range("A4:S" & u1)
            .Header = xlYes
            .MatchCase = False
            .Orientation = xlTopToBottom
            .SortMethod = xlPinYin
            .Apply
        End With
        'Númeramos las filas y copiamos el archivo a la hoja LVTXT
        If h1.[B5] <> "" Then h1.[B5] = 1
        If h1.[B6] <> "" Then h1.[B6] = 2
        If u1 > 6 Then h1.Range("B5:B6").AutoFill Destination:=h1.Range("B5:B" & u1)
        h1.Range("A5:S" & u1).Copy h3.Range("A1")
    End If
    'Configuramos 17 columnas en el listbox1
    ListBox1.ColumnCount = 17
    ListBox1.TextAlign = fmTextAlignRight
    ListBox1.ColumnHeads = False
    ListBox1.ColumnWidths = "25;15;60;40;60;20;60;160;60;60;60;60;60;60;60;60;60"
    'Llenamos la lista
    ListBox1.RowSource = h3.Name & "!A1:Q" & h3.Range("A" & Rows.Count).End(xlUp).Row
    'Configuramos 8 columnas en el listbox2 PARA LOS TOTALES
    ListBox2.ColumnCount = 8
    ListBox2.TextAlign = fmTextAlignRight
    ListBox2.ColumnHeads = False
    ListBox2.ColumnWidths = "60;60;60;60;60;60;60;60"
    'Llenamos la lista
    ListBox2.RowSource = h1.Name & "!Z2:AG2" '& h1.Range("Z" & Rows.Count).End(xlUp).Row
    Application.ScreenUpdating = True
End Sub

Encontré un detalle a la macro, prueba con esta

Private Sub CommandButton1_Click()
'Act.Por Dante Amor
    Application.ScreenUpdating = False
    Set h1 = Sheets("LVIVA")
    Set h2 = Sheets("LVI")
    Set h3 = Sheets("LVTXT")
    h3.Cells.ClearContents
    h1.Columns("A:S").ClearContents
    h1.Cells(2, 21) = Val(txtPeriodo.Value)
    u2 = h2.Range("A" & Rows.Count).End(xlUp).Row
    'Filtramos los datos
    h2.Range("A1:S" & u2).AdvancedFilter _
        Action:=xlFilterCopy, _
        CriteriaRange:=Range("LVIVA!LVIVACriterios"), _
        CopyToRange:=h1.Range("A4"), Unique:=False
    'Ordenamos los datos primero por numero de documento, fecha y numero de control
    u1 = h1.Range("A" & Rows.Count).End(xlUp).Row
    If u1 > 4 Then
        With h1.Sort
            .SortFields.Clear
            .SortFields.Add Key:=h1.Range("E5:E" & u1)
            .SortFields.Add Key:=h1.Range("C5:C" & u1)
            .SortFields.Add Key:=h1.Range("D5:D" & u1)
            .SetRange h1.Range("A4:S" & u1)
            .Header = xlYes
            .MatchCase = False
            .Orientation = xlTopToBottom
            .SortMethod = xlPinYin
            .Apply
        End With
        'Númeramos las filas y copiamos el archivo a la hoja LVTXT
        If h1.[B5] <> "" Then h1.[B5] = 1
        If h1.[B6] <> "" Then h1.[B6] = 2
        If u1 > 6 Then h1.Range("B5:B6").AutoFill Destination:=h1.Range("B5:B" & u1)
        h1.Range("A5:S" & u1).Copy h3.Range("A1")
    End If
    'Configuramos 17 columnas en el listbox1
    ListBox1.ColumnCount = 17
    ListBox1.TextAlign = fmTextAlignRight
    ListBox1.ColumnHeads = False
    ListBox1.ColumnWidths = "25;15;60;40;60;20;60;160;60;60;60;60;60;60;60;60;60"
    'Llenamos la lista
    ListBox1.RowSource = h3.Name & "!A1:Q" & h3.Range("A" & Rows.Count).End(xlUp).Row
    'Configuramos 8 columnas en el listbox2 PARA LOS TOTALES
    ListBox2.ColumnCount = 8
    ListBox2.TextAlign = fmTextAlignRight
    ListBox2.ColumnHeads = False
    ListBox2.ColumnWidths = "60;60;60;60;60;60;60;60"
    'Llenamos la lista
    ListBox2.RowSource = h1.Name & "!Z2:AG2" '& h1.Range("Z" & Rows.Count).End(xlUp).Row
    Application.ScreenUpdating = True
End Sub

Con esta macro no es necesaria la tercera hoja, la carga en el listbox se hace directamente de la hoja LVIVA, con esto se ahorra la copia, ahora debe ser más rápida.

Private Sub CommandButton1_Click()
'Act.Por Dante Amor
    Application.ScreenUpdating = False
    Set h1 = Sheets("LVIVA")
    Set h2 = Sheets("LVI")
    h1.Columns("A:S").ClearContents
    h1.Cells(2, 21) = Val(txtPeriodo.Value)
    u2 = h2.Range("A" & Rows.Count).End(xlUp).Row
    'Filtramos los datos
    h2.Range("A1:S" & u2).AdvancedFilter Action:=xlFilterCopy, _
        CriteriaRange:=h1.Range("LVIVACriterios"), CopyToRange:=h1.Range("A4"), Unique:=False
    'Configuramos 17 columnas en el listbox1
    ListBox1.ColumnCount = 17
    ListBox1.TextAlign = fmTextAlignRight
    ListBox1.ColumnHeads = False
    ListBox1.ColumnWidths = "25;15;60;40;60;20;60;160;60;60;60;60;60;60;60;60;60"
    ListBox1 = ""
    'Configuramos 8 columnas en el listbox2 PARA LOS TOTALES
    ListBox2.ColumnCount = 8
    ListBox2.TextAlign = fmTextAlignRight
    ListBox2.ColumnHeads = False
    ListBox2.ColumnWidths = "60;60;60;60;60;60;60;60"
    ListBox2 = ""
    'Ordenamos los datos primero por numero de documento, fecha y numero de control
    u1 = h1.Range("A" & Rows.Count).End(xlUp).Row
    If u1 > 4 Then
        With h1.Sort
            .SortFields.Clear
            .SortFields.Add Key:=h1.Range("E5:E" & u1)
            .SortFields.Add Key:=h1.Range("C5:C" & u1)
            .SortFields.Add Key:=h1.Range("D5:D" & u1)
            .SetRange h1.Range("A4:S" & u1)
            .Header = xlYes
            .MatchCase = False
            .Orientation = xlTopToBottom
            .SortMethod = xlPinYin
            .Apply
        End With
        'Númeramos las filas y copiamos el archivo a la hoja LVTXT
        If h1.[B5] <> "" Then h1.[B5] = 1
        If h1.[B6] <> "" Then h1.[B6] = 2
        If u1 > 6 Then h1.Range("B5:B6").AutoFill Destination:=h1.Range("B5:B" & u1)
        'Llenamos la lista
        ListBox1.RowSource = h1.Name & "!A5:Q" & u1
        'Llenamos la lista
        ListBox2.RowSource = h1.Name & "!Z2:AG2"
    End If
    Application.ScreenUpdating = True
End Sub

¡Gracias! 

wauuuuu

EXCELENTE!!!!!!!!!!!!!!!!!!!

Muchas gracias funciona de maravilla

Duda 1

En el segundo código que me enviaste en esta línea

'Llenamos la lista
    ListBox2.RowSource = h1.Name & "!Z2:AG2" '& h1.Range("Z" & Rows.Count).End(xlUp).Row
    Application.ScreenUpdating = True
End Sub

hay un apostrofe  ('&...) esto comvirte al codigo en un comentario. Asi l hiciste?? o lo corrijo quitando el apostrofe.

Duda 2

despues de copiar los datos filtrados a la hoja LVTXT necesito borrar las ultimas dos columnas (columnas r y s) ¿Cómo lo hago?

Gracias

Para la duda 1, no quites el apóstrofe.

Para la duda 2, h3.Columns("R:S"). Clearcontents, puedes poner la línea antes de esta línea ListBox1. RowSource

¡Gracias!

Que puedo decir siempre me dejas sin palabras.

El código es perfecto

Gracias

Hola Dante,

El código que me enviaste funciona muy bien pero no vi un pequeño detalle. La siguiente línea de código debería de numerar los registros existentes en la hoja LVIVA. Esta numeración debería de aparecer en la columna b de dicha hoja pero no se esta numerando.

'Númeramos las filas y copiamos el archivo a la hoja LVTXT
        If h1.[B5] <> "" Then h1.[B5] = 1
        If h1.[B6] <> "" Then h1.[B6] = 2
        If u1 > 6 Then h1.Range("B5:B6").AutoFill Destination:=h1.Range("B5:B" & u1)
        h1.Range("A5:S" & u1).Copy h3.¿Range("A1")

Podrías ayudarme?

Gracias

¿Y cuántas filas hay?

Puedes enviarme tu archivo para saber con cuál macro estás trabajando

Añade tu respuesta

Haz clic para o

Más respuestas relacionadas