Saltar al contenido

Adaptar código macro de una planilla a otra


Recommended Posts

publicado

Estimados necesitaba hacer una función que entregue un valor de acuerdo a dos celdas y que luego de tener ese valor, en otra celda, busque en una columna si se repite el numero de una celda, después si se repite utilizar los valores de las columnas aledañas a las celdas en donde se encontraron igualdades para hacer un calculo de precio según el valor de estas.

Primero estuve tratando sin macros pero no se me ocurrió como. Después me ayudaron con esta macro que realiza el calculo en una planilla pequeña, ahora cuando intente realizarlo en la planilla real no pude. Adjunto planilla Ejemplo y planilla Real con la macro no funcionando.

Este es el macro que funciona en la planilla de ejemplo son 2 modulos...

Modulo 1

Option Explicit

Option Base 1

Function BUSCARV2(valor1, valor2, area As Range, columna As Integer)

'Stop

'Este proceso crea una funcion personalizada en la cual busca dos valores

Dim i As Long

Dim resultado As Variant

Dim dim1 As Integer

Dim dim2 As Integer

'dim1 guarda la cantidad de filas del area

dim1 = area.Rows.Count

'dim2 guarda la cantidad de columnas del area

dim2 = area.Columns.Count

For i = 1 To dim1

If area.Cells(i, 1).Value = valor1 Then

If area.Cells(i, 2).Value = valor2 Then

resultado = area.Cells(i, columna).Value

Exit For

End If

End If

Next i

BUSCARV2 = resultado

End Function

Function BUSCARV3(TRA As String, CAMION As Integer, qvale As Double) As Double

Stop

'Dim qvale As Double

Dim filas As Long

'qvale = Val(ActiveCell.Offset(0, -1))

Dim mD, d, SumPeso As Double

'filas = Application.WorksheetFunction.CountA("A1:A65000")

'mD = Range("A1:E1").Offset(filas, 0)

mD = Range("A2").CurrentRegion

For d = 2 To UBound(mD, 1)

If mD(d, 3) = TRA And _

mD(d, 4) = CAMION And _

mD(d, 5) = qvale Then

SumPeso = SumPeso + mD(d, 1)

End If

Next

BUSCARV3 = mD(d, 1) * qvale / SumPeso

End Function

Sub BUSCARxPRECIO()

Dim TRA As String, CAMION As Integer, qvale As Double

TRA = ActiveCell.Offset(0, -3)

CAMION = ActiveCell.Offset(0, -2)

qvale = ActiveCell.Offset(0, -1)

Dim mD, d, SumPeso As Double

mD = Range("A1").CurrentRegion

For d = 2 To UBound(mD, 1)

If mD(d, 3) = TRA And _

mD(d, 4) = CAMION And _

mD(d, 5) = qvale Then

SumPeso = SumPeso + mD(d, 1)

End If

Next

'BUSCARV3 = mD(d, 1) * qVALE / SumPeso

End Sub

Modulo 2

Option Explicit

Option Base 1

Sub BUSCARxVALOR()

Dim f

f = Application.WorksheetFunction.CountA(Range("E:E")) + 1

Range("AA:AX").ClearContents

Range("E2:F" & f).ClearContents

Dim mP

Dim p

Dim mX

Dim mS

Dim s

Dim v1

Dim v2

mP = Sheets("PROVEEDORES").Range("A1").CurrentRegion

mS = Sheets("SERVICIOS").Range("A1").CurrentRegion

mX = Sheets("SERVICIOS").Range("A1").CurrentRegion

For s = 2 To UBound(mS, 1)

For p = 1 To UBound(mP, 1)

If mS(s, 3) = mP(p, 1) And _

mS(s, 4) = mP(p, 2) Then

mS(s, 5) = mP(p, 3)

Exit For

End If

Next

Next

Range("A1").Resize(s - 1, 5) = mS

'Stop

ORDENAR

Application.ScreenUpdating = False

VALORESxUNICOS

IMPORTES

Range("AA:AX").ClearContents

Application.ScreenUpdating = True

End Sub

Sub IMPORTES()

Dim mS

Dim s

Dim abc

Dim mI, i

mS = Sheets("SERVICIOS").Range("A1").CurrentRegion

mI = Range("AA1").CurrentRegion

'ReDim Preserve mS(s, 6)

For s = 2 To UBound(mS, 1)

abc = mS(s, 2) & "_" & mS(s, 3) & "_" & mS(s, 4)

For i = 2 To UBound(mI, 1)

If abc = mI(i, 1) Then

'Stop

mS(s, 5) = mI(i, 3)

mS(s, 6) = mS(s, 1) * mI(i, 4)

Exit For

End If

Next

Next

Range("A1").Resize(s - 1, 6) = mS

End Sub

Sub VALORESxUNICOS()

Dim mS

Dim s

Dim abc As String, f As Long, r As Range

mS = Sheets("SERVICIOS").Range("A1").CurrentRegion

f = 1

abc = mS(f, 2) & "_" & mS(f, 3) & "_" & mS(f, 4)

Range("AA" & f) = abc

Range("AB" & f) = mS(f, 1)

Range("AC" & f) = mS(f, 5)

Range("AD" & f) = "Valor#"

For s = 2 To UBound(mS, 1)

abc = mS(s, 2) & "_" & mS(s, 3) & "_" & mS(s, 4)

On Error Resume Next

If Range("AA" & f) = abc Then

'Range("AB" & s - 1) = Range("AB" & s - 1) + mS(s, 5)

'n_a_d_a

Range("AB" & f) = mS(s, 1) + Range("AB" & f)

Else

f = f + 1

Range("AA" & f) = mS(s, 2) & "_" & mS(s, 3) & "_" & mS(s, 4)

Range("AB" & f) = mS(s, 1)

Range("AC" & f) = mS(s, 5)

End If

Next

'Stop

Set r = Range("AA1")

f = 0

Do

f = f + 1

If r.Offset(f, 0) = "" Then Exit Do

r.Offset(f, 3) = r.Offset(f, 2) / r.Offset(f, 1)

Loop

End Sub

Sub ORDENAR()

Dim f

f = Application.WorksheetFunction.CountA(Range("A:A"))

ActiveWorkbook.Worksheets("SERVICIOS").Sort.SortFields.Clear

ActiveWorkbook.Worksheets("SERVICIOS").Sort.SortFields.Add Key:=Range("B2:B" & f _

), SortOn:=xlSortOnValues, Order:=xlAscending, DataOption:=xlSortNormal

ActiveWorkbook.Worksheets("SERVICIOS").Sort.SortFields.Add Key:=Range("C2:C" & f _

), SortOn:=xlSortOnValues, Order:=xlAscending, DataOption:=xlSortNormal

ActiveWorkbook.Worksheets("SERVICIOS").Sort.SortFields.Add Key:=Range("D2:D" & f _

), SortOn:=xlSortOnValues, Order:=xlAscending, DataOption:=xlSortNormal

With ActiveWorkbook.Worksheets("SERVICIOS").Sort

.SetRange Range("A1:F" & f)

.Header = xlYes

.MatchCase = False

.Orientation = xlTopToBottom

.SortMethod = xlPinYin

.Apply

End With

End Sub

Gracias Saludos

Planilla Real.xls

Ejemplo.xls

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.