Enlazar datos de otro libro
En esta oportunidad tengo en siguiente código y quiero enlazar otros datos de otro libro en mi archivo destino.
Los datos provienen de un libro llamado Químicos y debo extraer solo los datos de la columna M y P solamente al libro llamado Cemento
Me podrían ayudar con el tema.
Saludos.
Sub CEMENTO()
  Dim sh1 As Worksheet, sh2 As Worksheet
  Dim wb As Workbook
  Dim i As Long, fila As Long
  Dim col As String, m As Variant
  '
  Application.ScreenUpdating = False
  Set sh1 = Sheets("CEMENTO")
  sh1.Range("C5:J22, L5:S22, U5:AB22").ClearContents
  '
  Set wb = Workbooks.Open("\\10.7.10.1\calidad\SEGUIMIENTO HORA-HORA\MOLIENDA DE CEMENTO Y DESPACHOS FISICOS.xlsx", ReadOnly:=True)
  Set sh2 = Sheets("PERDIDA Y FINURA CEMENTO 2021")
  '
  For i = 7 To sh2.Range("A" & Rows.Count).End(3).Row
    If sh2.Range("A" & i).Value = sh1.Range("C2").Value Then
      Select Case sh2.Range("C" & i).Value
        Case "M3": col = "C"
        Case "M4": col = "L"
        Case "M5": col = "U"
        Case Else: col = ""
      End Select
      '
      If col <> "" Then
        fila = 5
        Do While sh1.Cells(fila, col).Value <> ""
          fila = fila + 1
        Loop
        m = sh2.Cells(i, "B").Value * 1
        sh1.Cells(fila, col) = IIf(m < 12 Or m = 24, m Mod 24 & ":00 AM", m Mod 12 & ":00 PM")
        sh1.Cells(fila, Columns(col).Column + 1).Resize(1, 7).Value = sh2.Range("D" & i).Resize(1, 7).Value
      End If
    End If
  Next
  wb.Close False
  Application.ScreenUpdating = True
  If sh1.Range("C5, L5, U5") = "" Then
    MsgBox "No hay datos reportados para este día"
  End If
End Sub
1 respuesta
 
                ¿Para extraerlos deben cumplir alguna condición?
En dónde los quieres poner, en cuál fila, en cuál columna, en cuál hoja.
 
                Si señor porque esos datos lo tenia en otra hoja.
https://drive.google.com/file/d/1iEKZBrpogzPefHCxuuJjO6UHzAPumd3V/view?usp=sharing
https://drive.google.com/file/d/1s7UzLvnlTlewiy-2hOdVPAG9kD2gXkVC/view?usp=sharing
https://drive.google.com/file/d/1WcpYWtsO64nvdGkAT-Z511CrUJuSCOLC/view?usp=sharing
 
                Me parece que compartiste la versión anterior del archivo "cemento", en la columna J aparece "molienda" y en tu imagen está en la K. Además no viene la macro.
 
                Si señor le envíe el anterior no el modificado.
Aquí le envío el modificado
https://drive.google.com/file/d/1WcpYWtsO64nvdGkAT-Z511CrUJuSCOLC/view?usp=sharing
 
                Buenos días



Buenos días, Dante
Tengo un error en otra hoja que es siguiente:
Esta es la línea del error y de donde proviene el dato de fecha
 
                Cambia esta línea:
Set sh2 = Sheets("CLINKER")Por esta:
Set sh2 = wb.Sheets("CLINKER")Prueba nuevamente.
Si ocurre el error, presiona el botón depurar, acerca el mouse a la instrucción: "A" & i
Pon el apuntador del mouse sobre la variable i
Debe aparecer una ventanita con el valor de i

Ahora ve a la hoja "CLINKER" del libro2 y ve a la celda A y el número de fila de la ventanita.
Revisa que realmente tengas una fecha, que no tengas un error de fórmula.
 
                En la i
Debes acercar el apuntador del mouse a la variable i
Y te debe aparecer un número

Mira mi ejemplo, en mi ejemplo aparece i = 2 a ti te debe aparecer un número.
Entonces vas a la hoja "CLINKER" del libro2 y ve a la celda A y el número de fila de la ventanita.
¿Dime qué tienes en esa celda?
Si en la celda tienes un error, entonces debes corregir el problema en la celda.
Tienes un error de datos en la hoja, debes corregir el problema en la hoja. No es un problema de la macro.
 
                Buen día, Dante
En la macro para cemento los datos están sobre las columnas a diferencia de clinker que están en las filas. No se si hay problemas por ese tema. Cuando evalúa la i se va a la fila 1632 y hay no hay dato.



 
                Ese es el problema, tienes #¡VALOR! En las celdas.
Corrige tu fórmula con SI. ERROR, por ejemplo:
=SI.ERROR(tuformula, "")
 
                El problema es que ese archivo no es de mi sección.
Cómo evaluó el tema de que los datos a extraer en clinker están solo en la fila
 
                Actualiza el código:
  For i = 7 To sh2.Range("A" & Rows.Count).End(3).Row
    If Not IsError(sh2.Range("A" & i)) Then
      If sh2.Range("A" & i).Value = sh1.Range("C2").Value Then
        Select Case sh2.Range("C" & i).Value
          Case "M3": col = "C"
          Case "M4": col = "L"
          Case "M5": col = "U"
          Case Else: col = ""
        End Select
        '
        If col <> "" Then
          fila = 5
          Do While sh1.Cells(fila, col).Value <> ""
            fila = fila + 1
          Loop
          m = sh2.Cells(i, "B").Value * 1
          sh1.Cells(fila, col) = IIf(m < 12 Or m = 24, m Mod 24 & ":00 AM", m Mod 12 & ":00 PM")
          sh1.Cells(fila, Columns(col).Column + 1).Resize(1, 7).Value = sh2.Range("D" & i).Resize(1, 7).Value
        End If
      End If
    End If
  Next
                     
                OK, Ya había hablado con la otra sección para que corriegieran la fórmula.
Tengo el inconveniente en clinker que se pegan los datos de ambos hornos en las casillas del horno 1.

Le coloque otra variable fila
y debajo de fila fila = 5 habia colocado fila = 17, pero nada.

 
                Se supone que cuando hace la comparación de fecha y el caso se instala en la fila 5, luego hace la siguiente comparación para lanzarla a la fila 17.
Yo había hecho una prueba agregando la variabra fila1
fila = 5
fila1=17
fila1= fila1+1
 
                La primera en la fila 5, la segunda en la fila 17, la tercera en la fila 6, ¿la cuarta en la fila 18 y así sucesivamente?
 
                Buenas tardes, Dante
Hice esto aunque me quedo más largo
Sub CLINKER()
  Dim sh1 As Worksheet, sh2 As Worksheet
  Dim wb As Workbook
  Dim i As Long, fila As Long
  Dim col As String, m As Variant, horno As Integer
  '
  Set sh1 = Sheets("CLÍNKER")
  sh1.Range("C5:AE14, C17:AE26").ClearContents
    Application.ScreenUpdating = False
    Application.DisplayAlerts = False
    Application.StatusBar = False
  '
  Set wb = Workbooks.Open("\\10.7.10.1\calidad\SEGUIMIENTO HORA-HORA\CLINKERIZACION.xlsx", ReadOnly:=True)
  Set sh2 = Sheets("CLINKER")
  '
  For i = 2 To sh2.Range("A" & Rows.Count).End(3).Row
    If sh2.Range("A" & i).Value = sh1.Range("C2").Value Then
    If Not IsError(sh2.Range("A" & i)) Then
      Select Case sh2.Range("C" & i).Value
        Case "H01": col = "C"
        Case "H02": col = "C"
        Case Else: col = ""
      End Select
      '
      Select Case sh2.Range("C" & i).Value
        Case "H01": horno = 1
        Case "H02": horno = 2
        Case Else: col = ""
      End Select
      If (col <> "") And (horno = 1) Then
        fila = 5
        Do While sh1.Cells(fila, col).Value <> ""
        fila = fila + 1
        Loop
        m = sh2.Cells(i, "B").Value * 1
        sh1.Cells(fila, col) = IIf(m < 12 Or m = 24, m Mod 24 & ":00 AM", m Mod 12 & ":00 PM")
        sh1.Cells(fila, Columns(col).Column + 1).Resize(1, 27).Value = sh2.Range("g" & i).Resize(1, 27).Value
      End If
      If (col <> "") And (horno = 2) Then
        fila = 17
        Do While sh1.Cells(fila, col).Value <> ""
        fila = fila + 1
        Loop
        m = sh2.Cells(i, "B").Value * 1
        sh1.Cells(fila, col) = IIf(m < 12 Or m = 24, m Mod 24 & ":00 AM", m Mod 12 & ":00 PM")
        sh1.Cells(fila, Columns(col).Column + 1).Resize(1, 27).Value = sh2.Range("g" & i).Resize(1, 27).Value
      End If
    End If
  Next
  wb.Close False
    Application.ScreenUpdating = True
    Application.DisplayAlerts = True
    Application.StatusBar = False
  If sh1.Range("C5, C17") = "" Then
    MsgBox "No hay datos reportados para este día"
    End If
  End Sub
                     
                Igual se puede simplificar.
No me comentaste que existía la condición de "H01"
Cambia a esto los 2 select
      Select Case sh2.Range("C" & i).Value
        Case "H01": col = "C"
        Case "H02": col = "C"
        Case Else: col = ""
      End Select
      '
      Select Case sh2.Range("C" & i).Value
        Case "H01": horno = 1
        Case "H02": horno = 2
        Case Else: col = ""
      End Selectpor esto:
      Select Case sh2.Range("C" & i).Value
        Case "H01": col = "C": horno = 1
        Case "H02": col = "C": horno = 2
        Case Else: col = ""
      End Select
      '
                     
                Buenas tardes, Dante
La línea que me dijiste que cambiara
If sw = 0 Then fila = 5: sw = 1 Else fila = 17: sw = 0
esta es intercalando los datos.
En la columna C estados los datos del H01 y H02
En la C15 van los datos del H01
C17 van los los datos del H02
 
                Eso pediste:
La primera en la fila 5, la segunda en la fila 17, la tercera en la fila 6, ¿la cuarta en la fila 18 y así sucesivamente?
Si señor
 
                No puedo hacer pruebas porque no conozco la estructura de tus hojas. Ni tampoco mes estás proporcionando las condiciones completas
El error ya lo tenías en tu código.
Prueba esto:
Sub CLINKER()
  Dim sh1 As Worksheet, sh2 As Worksheet
  Dim wb As Workbook
  Dim i As Long, fila As Long
  Dim col As String, m As Variant, horno As Integer
  '
  Set sh1 = Sheets("CLÍNKER")
  sh1.Range("C5:AE14, C17:AE26").ClearContents
    Application.ScreenUpdating = False
    Application.DisplayAlerts = False
    Application.StatusBar = False
  '
  Set wb = Workbooks.Open("\\10.7.10.1\calidad\SEGUIMIENTO HORA-HORA\CLINKERIZACION.xlsx", ReadOnly:=True)
  Set sh2 = Sheets("CLINKER")
  For i = 2 To sh2.Range("A" & Rows.Count).End(3).Row
    If sh2.Range("A" & i).Value = sh1.Range("C2").Value Then
      If Not IsError(sh2.Range("A" & i)) Then
        Select Case sh2.Range("C" & i).Value
          Case "H01": col = "C": horno = 1
          Case "H02": col = "C": horno = 2
          Case Else: col = ""
        End Select
        If (col <> "") And (horno = 1) Then
          fila = 5
          Do While sh1.Cells(fila, col).Value <> ""
          fila = fila + 1
          Loop
          m = sh2.Cells(i, "B").Value * 1
          sh1.Cells(fila, col) = IIf(m < 12 Or m = 24, m Mod 24 & ":00 AM", m Mod 12 & ":00 PM")
          sh1.Cells(fila, Columns(col).Column + 1).Resize(1, 27).Value = sh2.Range("g" & i).Resize(1, 27).Value
        End If
        If (col <> "") And (horno = 2) Then
          fila = 17
          Do While sh1.Cells(fila, col).Value <> ""
          fila = fila + 1
          Loop
          m = sh2.Cells(i, "B").Value * 1
          sh1.Cells(fila, col) = IIf(m < 12 Or m = 24, m Mod 24 & ":00 AM", m Mod 12 & ":00 PM")
          sh1.Cells(fila, Columns(col).Column + 1).Resize(1, 27).Value = sh2.Range("g" & i).Resize(1, 27).Value
        End If
      End If
    End If
  Next
  '
  wb.Close False
  Application.ScreenUpdating = True
  If sh1.Range("C5, L5, U5") = "" Then
    MsgBox "No hay datos reportados para este día"
  End If
End Sub
                     
                Buenas tardes,
https://drive.google.com/file/d/1cymagDR9tw8l1SBzfZMX7rUX-8cQ_HUV/view?usp=sharing
https://drive.google.com/file/d/15ZVjjL8SYgxP42Sb-rY4o2pvCtfLOF6z/view?usp=sharing
Ok le envío los archivos que estoy utilizando.
Como le había comentado quiero que los datos de los hornos (H01 y H02) que están ene l archivo clinkerizacion hoja clinker, se copien en el archivo consulta de calidad hoja clinker según condición de fecha en cada horno.
En espera de sus comentarios.
Gracias
 
                Probaste la última macro que puse, solamente agregué End If y simplifiqué el case, supuse que ya te funcionaba.
 
                Ok funciono. Pensé que se podía simplificar lo que había hecho.
Quedo atento a la primera inquietud de coklocar los datos de color, so3 y cl a la hoja cemento.
 
                Buenos días, Dante
En esta ocasión resulta que deseo al igual que en el anterior hacer que la macro sea más corta y efiiente. Tengo lo siguiente
Sub MOLIENDA_CRUDO()
Set jh = Sheets("MOLIENDA DE CRUDO")
jh.Activate
Range(jh.Cells(5, "D"), jh.Cells(17, "S")).Select
Selection.ClearContents
Range(jh.Cells(20, "D"), jh.Cells(32, "S")).Select
Selection.ClearContents
Workbooks.Open Filename:="\\10.7.10.1\calidad\SEGUIMIENTO HORA-HORA\MOLIENDA DE CRUDO.xlsx", ReadOnly:=True
Set jhc = Sheets("CRUDO 1")
Set jhc2 = Sheets("CRUDO 2")
jhc.Activate
jhc.Cells(2, "C").Select
jhc.Cells(2, "C").End(xlDown).Select
Fila = ActiveCell.Row
While Not (jhc.Cells(Fila, "A") < jh.Cells(2, "C"))
    Fila = Fila - 1
Wend
Target = 0
Filam1 = 5
Filam2 = 20
Do While Target = 0
    If Not (jhc.Cells(Fila, "D") = Empty) Then
        If jhc.Cells(Fila, "A") = jh.Cells(2, "C") Then
                jh.Activate
                'jh.Cells(Filam1, "C") = jhc.Cells(Fila, "B").Value * 1
                'If jh.Cells(Filam1, "C") < 12 Then
                    'jh.Cells(Filam1, "C") = jh.Cells(Filam1, "C") & " AM"
                    'Else
                        'If jh.Cells(Filam1, "C") = 12 Then
                            'jh.Cells(Filam1, "C") = jh.Cells(Filam1, "C") & " PM"
                            'Else
                                'If jh.Cells(Filam1, "C") * 1 = 24 Or jh.Cells(Filam1, "C") * 1 = 0 Then
                                    'jh.Cells(Filam1, "C") = 0 & " AM"
                                    'Else
                                        'jh.Cells(Filam1, "C") = (jh.Cells(Filam1, "C") - 12) & " PM"
                                'End If
                        'End If
                'End If
                'jh.Cells(Filam1, "C") = jh.Cells(Filam1, "C")
                jh.Cells(Filam1, "D") = jhc.Cells(Fila, "C")
                For i = 5 To 19
                    jh.Cells(Filam1, i) = jhc.Cells(Fila, i + 1)
                Next i
                Filam1 = Filam1 + 1
        End If
    End If
        jhc.Activate
        If jhc.Cells(Fila, "C") = Empty Then
            Target = 1
        End If
    Fila = Fila + 1
Loop
'MOLINO DE CRUDO 2
jhc2.Activate
jhc2.Cells(2, "C").Select
jhc2.Cells(2, "C").End(xlDown).Select
Fila = ActiveCell.Row
While Not (jhc2.Cells(Fila, "A") < jh.Cells(2, "C"))
    Fila = Fila - 1
Wend
Target = 0
Filam1 = 5
Filam2 = 20
Do While Target = 0
    If Not (jhc2.Cells(Fila, "C") = Empty) Then
        If jhc2.Cells(Fila, "A") = jh.Cells(2, "C") Then
                jh.Activate
                'jh.Cells(Filam2, "C") = jhc2.Cells(Fila, "B").Value * 1
                'If jh.Cells(Filam2, "C") < 12 Then
                    'jh.Cells(Filam2, "C") = jh.Cells(Filam2, "C") & " AM"
                    'Else
                        'If jh.Cells(Filam2, "C") = 12 Then
                            'jh.Cells(Filam2, "C") = jh.Cells(Filam1, "C") & " PM"
                            'Else
                                'If jh.Cells(Filam1, "C") * 1 = 24 Or jh.Cells(Filam1, "C") * 1 = 0 Then
                                    'jh.Cells(Filam2, "C") = 0 & " AM"
                                    'Else
                                        'jh.Cells(Filam2, "C") = (jh.Cells(Filam2, "C") - 12) & " PM"
                                'End If
                        'End If
                'End If
                'jh.Cells(Filam2, "C") = jh.Cells(Filam2, "C")
                jh.Cells(Filam2, "D") = jhc2.Cells(Fila, "C")
                For i = 5 To 19
                    jh.Cells(Filam2, i) = jhc2.Cells(Fila, i + 1)
                Next i
                Filam2 = Filam2 + 1
        End If
        jhc2.Activate
    End If
     If jhc2.Cells(Fila, "C") = Empty Then
            Target = 1
     End If
    Fila = Fila + 1
Loop
If jh.Cells(5, "C") = Empty And jh.Cells(20, "C") = Empty Then
    MsgBox ("No hay datos reportados para este día")
End If
RET_MOLIENDA_CRUDO
jhc2.Activate
ActiveWindow.Close savechanges:=False
    jh.Activate
    'jh.Range("C5:S17").Select
    'ActiveWorkbook.Worksheets("MOLIENDA DE CRUDO").Sort.SortFields.Clear
    'ActiveWorkbook.Worksheets("MOLIENDA DE CRUDO").Sort.SortFields.Add2 Key:=Range("C5"), _
       'SortOn:=xlSortOnValues, Order:=xlAscending, DataOption:=xlSortNormal
    'With ActiveWorkbook.Worksheets("MOLIENDA DE CRUDO").Sort
        '.SetRange Range("C5:S17")
       '.Header = xlNo
       '.MatchCase = False
       '.Orientation = xlTopToBottom
       '.SortMethod = xlPinYin
       '.Apply
   'End With
    'jh.Range("C20:S32").Select
    'ActiveWorkbook.Worksheets("MOLIENDA DE CRUDO").Sort.SortFields.Clear
    'ActiveWorkbook.Worksheets("MOLIENDA DE CRUDO").Sort.SortFields.Add2 Key:=Range("C20"), _
        'SortOn:=xlSortOnValues, Order:=xlAscending, DataOption:=xlSortNormal
    'With ActiveWorkbook.Worksheets("MOLIENDA DE CRUDO").Sort
        '.SetRange Range("C20:S32")
        '.Header = xlNo
        '.MatchCase = False
        '.Orientation = xlTopToBottom
        '.SortMethod = xlPinYin
        '.Apply
   'End With
End SubLa idea es copaiar los datos de has hojas crudo1, crudo2 y retenido del libro molienda de crudo al libro consultas calidad en la hoja molienda de crudo en cada molino.


Con dependencia de fecha y horas diferentes para los retenidos como la imagen.
En espera de sus comentarios
- Compartir respuesta
 
        

