Saltar al contenido

AYUDA URGENTE


Recommended Posts

publicado

La siguiente macro me permite ordenar datos segun el apellido paterno, lo que quisiera saber es como hacer para aumentar mayor ordenes, por ejemplo que ahora ordene como el apellido materno, como lo adinaria

Sub macro22()
If [L2] = "ascendente" And [L5] = "Paterno" Then
    For x = 2 To 40
        For y = x + 1 To 41
        If Cells(x, "E") > Cells(y, "E") Then
                Variable = Cells(x, "E")
                Cells(x, "E") = Cells(y, "E")
                Cells(y, "E") = Variable
                Variablea = Cells(x, "F")
                Cells(x, "F") = Cells(y, "F")
                Cells(y, "F") = Variablea
                Variableb = Cells(x, "G")
                Cells(x, "G") = Cells(y, "G")
                Cells(y, "G") = Variableb
                Variablec = Cells(x, "H")
                Cells(x, "H") = Cells(y, "H")
                Cells(y, "H") = Variablec
                      
        End If
        Next
    Next
Else
    For x = 2 To 40
        For y = x + 1 To 41
            If Cells(x, "E") < Cells(y, "E") Then
                Variable = Cells(x, "E")
                Cells(x, "E") = Cells(y, "E")
                Cells(y, "E") = Variable
                Variablea = Cells(x, "F")
                Cells(x, "F") = Cells(y, "F")
                Cells(y, "F") = Variablea
                Variableb = Cells(x, "G")
                Cells(x, "G") = Cells(y, "G")
                Cells(y, "G") = Variableb
                Variablec = Cells(x, "H")
                Cells(x, "H") = Cells(y, "H")
                Cells(y, "H") = Variablec
                      
            End If
        Next
    Next

End If

               
End Sub

publicado

sube un archivo, eso que solicitas se puede hacer con mucho menos lineas de las que estas usando, claro una vez viendo la estructura de los datos es mas facil ver las opciones que hay.

publicado
Hace 29 minutos , Dr Hyde dijo:

sube un archivo, eso que solicitas se puede hacer con mucho menos lineas de las que estas usando, claro una vez viendo la estructura de los datos es mas facil ver las opciones que hay.

 

Gracias por la respuesta, lo que sucede es que recién soy estudiante y el trabajo se basa en el ordenamiento con el método de burbuja, así que se me ocurrió hacerlo de esa manera. Envio el archivo que dice trabajo parcial, es la hoja con el nombre trabajo parcial. Ahi estan 4 macros ,TRABAJO PARCIAL.xlsm, cada uno con su orden respectivo, lo que queria saber era como juntar las 4 operaciones en uno solo.

Saludos

publicado

la unica que se me hace viable es usar if... elseif..else...endif

por ejemplo

 If [L2] = "ascendente" And [L5] = "Paterno" Then

instrucciones

elseif [L2] = "ascendente" And [L5] = "materno" Then

instrucciones

elseif [L2] = "ascendente" And [L5] = "nombre" Then

instrucciones

elseif [L2] = "ascendente" And [L5] = "profesion" Then

instrucciones

endif

asi tienes las 4 macros en 1 sola

publicado
Hace 11 minutos , Dr Hyde dijo:

la unica que se me hace viable es usar if... elseif..else...endif

por ejemplo

 If [L2] = "ascendente" And [L5] = "Paterno" Then

instrucciones

elseif [L2] = "ascendente" And [L5] = "materno" Then

instrucciones

elseif [L2] = "ascendente" And [L5] = "nombre" Then

instrucciones

elseif [L2] = "ascendente" And [L5] = "profesion" Then

instrucciones

endif

asi tienes las 4 macros en 1 sola

pero en el caso sea descendente tambien lo crearia con el elseif??

publicado

if... elseif...endif, valida cual condicion se cumple antes de ejecutar la macro por ejemplo, si la primera condicion no se cumple salta a la 2a y si esta no se cumple salta a la 3era y asi sucesivamente hasta llegar al endif, por ejemplo:

If [L2] = "ascendente" And [L5] = "Paterno" Then

instrucciones

elseif [L2] = "ascendente" And [L5] = "materno" Then

instrucciones

elseif [L2] = "descendente"  And [L5] = "paterno" Then

instrucciones

elseif [L2] = "descendente" And [L5] = "materno" Then

instrucciones

endif

publicado

Buenas @helard

Usa

Sub Ordenate()
    Dim orden As String     'VARIABLE PARA TOMAR EL TIPO DE ORDEN
    Dim cola  As String     'VARIABLE PARA TOMAR LA SELECCIÓN DE COLUMNA ORDEN
    Dim iOrde As Integer    'VARIABLE TIPO ORDEN
    Dim iCola As Long       'VARIABLE COLUMNA ORDEN
    Dim uFils As Long       'VARIABLE FILAS A ORDENAR

' TOMAMOS EL VALOR DE LA COLUMNA A ORDENAR
    cola = Hoja9.Range("L5").Value

' TOMAMOS EL TIPO DE ORDENAMIENTO
    orden = Hoja9.Range("L2").Value
    
' TOMAMOS LA ÚLTIMA FILA USADA DE CADA COLUMNA Y SE TOMA EL MAYOR
    uFils = WorksheetFunction.Max(Hoja9.Cells(Hoja9.Rows.Count, 5).End(xlUp).Row, _
                                  Hoja9.Cells(Hoja9.Rows.Count, 6).End(xlUp).Row, _
                                  Hoja9.Cells(Hoja9.Rows.Count, 7).End(xlUp).Row, _
                                  Hoja9.Cells(Hoja9.Rows.Count, 8).End(xlUp).Row)

                                  
' VERIFICAMOS QUE SE INDICO COLUMNA A ORDENAR
    If cola = "" Then Exit Sub
    
' VERIFICAMOS QUE EXISTEN DATOS A ORDENAR
    If uFils < 2 Then Exit Sub
    
' SE INDICA EL TIPO DE ORDEN
    iOrde = IIf(orden = "ascendente", 1, 2)
    
' SE INDICA LA COLUMNA A ORDENAR
    On Error Resume Next
    iCola = WorksheetFunction.Match(cola, Array("Paterno", "Materno", "Nombre", "Profesion"), 0) + 4
    On Error GoTo 0

' SE VERIFICA QUE EL VALOR EXISTIA
    If iCola < 5 Then Exit Sub
    
' SE PROCEDE A ORDENAR
    Hoja9.Range("E2:H" & uFils).Sort key1:=Hoja9.Cells(2, iCola), order1:=iOrde
End Sub

 

En el código posees explicación de cada función usada

 

Un saludo

publicado

Aquí dejo una macro para ordenar por el método burbuja. de acuerdo con el archivo adjunto.

Con arrays en lugar de celdas, iría bastante mas rápido.

Sub OrdenarMétodoBurbuja()
pf = [E1].End(xlDown).Row + 1
y = Rows(1).Find([L5]).Column
Application.ScreenUpdating = False
For x = 2 To pf - 1
   Application.StatusBar = "Procesando fila: " & x
   For x1 = x + 1 To pf - 1
      If [L2] = "ascendente" And Cells(x1, y) < Cells(x, y) Or _
         [L2] = "descendente" And Cells(x1, y) > Cells(x, y) Then
         Range("E" & x & ":H" & x).Copy Range("E" & pf)
         Range("E" & x1 & ":H" & x1).Copy Range("E" & x)
         Range("E" & pf & ":H" & pf).Copy Range("E" & x1)
         Range("E" & pf & ":H" & pf).ClearContents
      End If
   Next
Next
Application.StatusBar = False
End Sub

 

TRABAJO PARCIAL.xlsm

  • Silvia bloqueó este tema

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.