Saltar al contenido

Optimizar una Macro


hans123

Recommended Posts

publicado

Estimados,

Soy nuevo en este foro y desde ya agradezco la creación en este foro, sus importantes aportes y la ayuda que me puedan brindar.

Necesito que me puedan ayudar por favor, en la optimización de una macro (realizada en Excel 2007) , ya que, se demora bastante tiempo en ejecutarla y como la ocupo varias veces al día se me hace MUY necesario el poder hacer que corra mas rápido.

He probado con distintos códigos, entre ellos, agregar al inicio y al final de la macro, las siguientes sentencias.

Al inicio:

Application.ScreenUpdating = False

Application.Calculation = xlCalculationManual

Application.EnableEvents = False

ActiveSheet.DisplayPageBreaks = False

Al final:

Application.ScreenUpdating = True

Application.Calculation = xlCalculationAutomatic

Application.EnableEvents = True

ActiveSheet.DisplayPageBreaks = True

Application.CutCopyMode = False

Entre otras cosas, pero NADA me resulta... el proceso se sigue demorando aproximadamente 20 minutos.

Así que les pido de favor que me puedan ayudar!!

Muchas Gracias!

PD: Les adjunto el código:

Public Const hoja_macro As Integer = 1 ' numero (indice) de la hoja macro

Public Const hoja_frecuencia As Integer = 2 'numero (indice) de la hoja frecuencia

Public Const hoja_velocidad As Integer = 3 'numero (indice) de la hoja velocidad

Public Const hoja_distancia As Integer = 4 'numero (indice) de la hoja ditancia

Public Const hoja_capacidad As Integer = 5 'numero (indice) de la hoja capacidad

Public Const hoja_flota As Integer = 6 'numero (indice) de la hoja flota

Public Const max_servicio As Integer = 800 ' maxima cantidad de servicios del sistema

Public Const max_periodo As Integer = 29 ' cantidad de periodos

' funcion que retorna la fila donde se encuentra el servicio buscado

Function buscar_ss(servicio As String, sentido As String, indice_hoja As Integer)

For i = 1 To max_servicio

If UCase(Sheets(indice_hoja).Cells(i, 2)) = UCase(servicio) And UCase(Sheets(indice_hoja).Cells(i, 3)) = UCase(sentido) Then

buscar_ss = i

Exit Function

End If

Next

End Function

Sub traspone()

Application.ScreenUpdating = False

Application.Calculation = xlCalculationManual

Application.EnableEvents = False

ActiveSheet.DisplayPageBreaks = False

limpiar ' funcion para limpiar datos de hoja macro

fila = 2 ' para ir escribiendo a partir de la fila 2 en hoja macro

For i = 1 To max_servicio ' recorrer filas hasta el maximo de servicios definidos

For j = 1 To max_periodo ' recorrer columnas hasta la cantidad de periodos definidos

If Sheets(hoja_frecuencia).Cells(i + 6, 1) <> "" Then ' recorrer filas hasta pillar celda vacio, lo que significa que no hay mas datos

'aqu se va rellenando fila por fila la informacion en la hoja macro

'///////////////////////////////////////////

Sheets(hoja_macro).Cells(fila, 1) = Sheets(hoja_frecuencia).Cells(i + 6, 1) ' unidad

Sheets(hoja_macro).Cells(fila, 2) = Sheets(hoja_frecuencia).Cells(i + 6, 2) ' servicio

Sheets(hoja_macro).Cells(fila, 3) = Sheets(hoja_frecuencia).Cells(i + 6, 3) ' sentido

Sheets(hoja_macro).Cells(fila, 4) = Sheets(hoja_frecuencia).Cells(1, j + 3) ' periodo

Sheets(hoja_macro).Cells(fila, 5) = Sheets(hoja_frecuencia).Cells(buscar_ss(Sheets(hoja_frecuencia).Cells(i + 6, 2), Sheets(hoja_frecuencia).Cells(i + 6, 3), 2), j + 3)

Sheets(hoja_macro).Cells(fila, 6) = Sheets(hoja_velocidad).Cells(buscar_ss(Sheets(hoja_frecuencia).Cells(i + 6, 2), Sheets(hoja_frecuencia).Cells(i + 6, 3), 3), j + 3)

Sheets(hoja_macro).Cells(fila, 7) = Sheets(hoja_distancia).Cells(buscar_ss(Sheets(hoja_frecuencia).Cells(i + 6, 2), Sheets(hoja_frecuencia).Cells(i + 6, 3), 4), j + 3)

Sheets(hoja_macro).Cells(fila, 8) = Sheets(hoja_capacidad).Cells(buscar_ss(Sheets(hoja_frecuencia).Cells(i + 6, 2), Sheets(hoja_frecuencia).Cells(i + 6, 3), 5), j + 3)

Sheets(hoja_macro).Cells(fila, 9) = Sheets(hoja_flota).Cells(buscar_ss(Sheets(hoja_frecuencia).Cells(i + 6, 2), Sheets(hoja_frecuencia).Cells(i + 6, 3), 6), j + 3)

fila = fila + 1

End If

Next

Next

MsgBox "proceso terminado con exito !! revisa resultados"

Application.ScreenUpdating = True

Application.Calculation = xlCalculationAutomatic

Application.EnableEvents = True

ActiveSheet.DisplayPageBreaks = True

Application.CutCopyMode = False

End Sub

Sub limpiar() ' funcion para limpiar datos de la hoja macro

'

' limpiar Macro

'

'

Range("A2:I2").Select

Range(Selection, Selection.End(xlDown)).Select

Range(Selection, Selection.End(xlDown)).Select

Range(Selection, Selection.End(xlDown)).Select

Range(Selection, Selection.End(xlDown)).Select

Range(Selection, Selection.End(xlDown)).Select

Range(Selection, Selection.End(xlDown)).Select

Range(Selection, Selection.End(xlDown)).Select

Range(Selection, Selection.End(xlDown)).Select

Range(Selection, Selection.End(xlDown)).Select

Range(Selection, Selection.End(xlDown)).Select

Range(Selection, Selection.End(xlDown)).Select

Range(Selection, Selection.End(xlDown)).Select

Range(Selection, Selection.End(xlDown)).Select

Range(Selection, Selection.End(xlDown)).Select

Range(Selection, Selection.End(xlDown)).Select

Selection.ClearContents

End Sub

' funcion para agregar letra T a los troncales

Sub formato()

For i = 1 To 23000

If Sheets(hoja_macro).Cells(i, 1) Like "*T*" Then

Sheets(hoja_macro).Cells(i, 2) = "T" & Sheets(hoja_macro).Cells(i, 2)

End If

Next

End Sub

Archivado

Este tema está ahora archivado y está cerrado a más respuestas.

  • 109 ¿Te parecen útiles los tips de las funciones? (ver tema completo)

    1. 1. ¿Te parecen útiles los tips de las funciones?


      • No
      • Ni me he fijado en ellos

  • Ayúdanos a mejorar la comunidad

    • Donaciones recibidas este mes: 0.00 EUR
      Objetivo: 130.00 EUR
  • Archivos

  • Estadísticas de descargas

    • Archivos
      188
    • Comentarios
      98
    • Revisiones
      29

    Más información sobre "Cambios en el Control Horario"
    Última descarga
    Por pegones1

    4    1

  • Crear macros Excel

  • Mensajes

    • Hola, veo que tienes 365, así que esta forma funcionará   Almacen.xlsx
    • Buenos días  @LeandroA espero estes bien Tengo un caso idéntico al planteado en la siguiente pregunta: Sin embargo, a diferencia de quien planteo originalmente la pregunta al correr el código no obtengo ningún resultado podrían ayudarme a resolver este inconveniente y que al hacer click en el Botón Guardar (CommandButton3) del Formulario RCS (frmrcs) el archivo pdf quede configurado con orientación vertical, márgenes superior, inferior, derecho e izquierdo = 1 y en página tamaño carta. Si acaso influye uso Microsoft Excel LTSC MSO (versión 2209 Compilación16.0.1.15629.20200) de 64 bits Mucho le sabre agradecer la ayuda que me pueda dar  RCS PRUEBA - copia.xlsm
    • @JSDJSDCon gusto mi estimado Para la opción 1: Sub Surtirhastadondealcanse() Dim ws As Worksheet Set ws = ThisWorkbook.Sheets(1) Dim filaInicio As Integer: filaInicio = 4 Dim filaFin As Integer: filaFin = 7 Dim colInventario As Integer: colInventario = 2 Dim colSolicitudesInicio As Integer: colSolicitudesInicio = 4 ' Columna C Dim colResultadoInicio As Integer: colResultadoInicio = 9 ' Columna I Dim colTotalSurtido As Integer: colTotalSurtido = 12 ' Columna L Dim colFinalInventario As Integer: colFinalInventario = 13 ' Columna M Dim numClientes As Integer: numClientes = 3 Dim fila As Integer, i As Integer For fila = filaInicio To filaFin Dim inventario As Double inventario = Val(ws.Cells(fila, colInventario).Value) Dim solicitudes(1 To 3) As Double Dim surtido(1 To 3) As Variant Dim totalSurtido As Double: totalSurtido = 0 ' Leer solicitudes For i = 1 To numClientes If IsNumeric(ws.Cells(fila, colSolicitudesInicio + i - 1).Value) Then solicitudes(i) = CDbl(ws.Cells(fila, colSolicitudesInicio + i - 1).Value) Else solicitudes(i) = 0 End If surtido(i) = "POR FALTA STOCK" Next i ' Surtir de acuerdo al inventario disponible For i = 1 To numClientes If solicitudes(i) > 0 Then If inventario >= solicitudes(i) Then surtido(i) = solicitudes(i) inventario = inventario - solicitudes(i) totalSurtido = totalSurtido + solicitudes(i) ElseIf inventario > 0 Then surtido(i) = inventario totalSurtido = totalSurtido + inventario inventario = 0 Else surtido(i) = "POR FALTA STOCK" End If End If Next i ' Escribir resultados en las columnas correspondientes para cada cliente For i = 1 To numClientes With ws.Cells(fila, colResultadoInicio + i - 1) If surtido(i) = "POR FALTA STOCK" Then .Value = surtido(i) .Font.Color = vbRed Else .Value = surtido(i) .Font.Color = vbBlack End If End With Next i ' Escribir total surtido y existencia final ws.Cells(fila, colTotalSurtido).Value = totalSurtido ws.Cells(fila, colFinalInventario).Value = inventario Next fila MsgBox "Resultado surtido cargado con éxito...", vbInformation End Sub Para la opción 2:   Sub surtirenpartesiguales() Dim ws As Worksheet Set ws = ThisWorkbook.Sheets(1) Dim filaInicio As Integer: filaInicio = 13 Dim filaFin As Integer: filaFin = 16 Dim colInventario As Integer: colInventario = 2 Dim colSolicitudesInicio As Integer: colSolicitudesInicio = 4 ' Columna C Dim colResultadoInicio As Integer: colResultadoInicio = 9 ' Columna I Dim colTotalSurtido As Integer: colTotalSurtido = 12 ' Columna L Dim colFinalInventario As Integer: colFinalInventario = 13 ' Columna M Dim numClientes As Integer: numClientes = 3 Dim fila As Integer, i As Integer For fila = filaInicio To filaFin Dim inventario As Double inventario = Val(ws.Cells(fila, colInventario).Value) Dim solicitudes(1 To 3) As Double Dim surtido(1 To 3) As Variant Dim totalSurtido As Double: totalSurtido = 0 Dim totalPedido As Double: totalPedido = 0 ' Leer solicitudes For i = 1 To numClientes If IsNumeric(ws.Cells(fila, colSolicitudesInicio + i - 1).Value) Then solicitudes(i) = CDbl(ws.Cells(fila, colSolicitudesInicio + i - 1).Value) totalPedido = totalPedido + solicitudes(i) Else solicitudes(i) = 0 End If surtido(i) = 0 Next i ' Si hay suficiente inventario, surtir lo que el cliente pide If inventario >= totalPedido Then For i = 1 To numClientes If solicitudes(i) > 0 And inventario >= solicitudes(i) Then surtido(i) = solicitudes(i) inventario = inventario - solicitudes(i) totalSurtido = totalSurtido + solicitudes(i) End If Next i Else ' Reparto base igualitario Dim baseSurtido As Long baseSurtido = Int(inventario / numClientes) For i = 1 To numClientes If solicitudes(i) > 0 Then If solicitudes(i) <= baseSurtido Then surtido(i) = solicitudes(i) inventario = inventario - solicitudes(i) totalSurtido = totalSurtido + solicitudes(i) Else surtido(i) = baseSurtido inventario = inventario - baseSurtido totalSurtido = totalSurtido + baseSurtido End If End If Next i ' Repartir sobrante restante uno por uno, respetando lo pedido Do While inventario > 0 For i = 1 To numClientes If surtido(i) < solicitudes(i) Then surtido(i) = surtido(i) + 1 totalSurtido = totalSurtido + 1 inventario = inventario - 1 If inventario = 0 Then Exit For End If Next i Loop End If ' Escribir resultados en las columnas correspondientes para cada cliente For i = 1 To numClientes With ws.Cells(fila, colResultadoInicio + i - 1) If surtido(i) = 0 Then .Value = "POR FALTA STOCK" .Font.Color = vbRed Else .Value = surtido(i) .Font.Color = vbBlack End If End With Next i ' Escribir total surtido y existencia final ws.Cells(fila, colTotalSurtido).Value = totalSurtido ws.Cells(fila, colFinalInventario).Value = inventario Next fila MsgBox "Resultado surtido cargado con éxito...", vbInformation End Sub Saludos, Diego
    • Buenos dias.  Estoy trabajando en una hoja para poder llevar un control de un pequeño almacén.  Tengo un pedido con varias líneas y "lotes" y necesito sacar las ubicaciones que coincidan con la referencia y lote que pone en el pedido. El problema viene cuando tengo la misma referencia y mismo lote en ubicaciones diferentes y necesito sacar la información en columnas diferentes. No se si  me he explicado bien, pero creo que con el ejemplo adjunto se entiende mejor. Agradecería mucho si me pudieran ayudar  Libro1.xlsx
    • Exelente solución mil gracias 
  • Visualizado recientemente

    • No hay usuarios registrado para ver esta página.
×
×
  • Crear nuevo...

Información importante

Echa un vistazo a nuestra política de cookies para ayudarte a tener una mejor experiencia de navegación. Puedes ajustar aquí la configuración. Pulsa el botón Aceptar, si estás de acuerdo.