简体   繁体   中英

Copy paste to another workbook with an if statement

I want to copy certain values from another sheet from another workbook in vba excel but im gettin err 1004. this is my code

Sub copiar()
    Dim rng As Range
    Dim cell As Range
    Dim rng2 As Range
    Dim cell2 As Range


    Set rng2 = Range("A2:A5")
    Set rng = Workbooks("perfumes.xlsx").Sheets("hoja").Range("A4:A10")


    For Each cell In rng2
        For Each cell2 In rng
            If cell2 = cell Then Workbooks("perfumes.xlsx").Worksheets("Hoja 1").Range("K" & cell2.Row).Copy Range("H" & cell.Row)
        Next cell2
    Next cell

End Sub

Cant realise where the error occur Im quite new to macros, migth need help, thanks

There's nothing wrong with your code, as such, the runtime error is a data problem so showing the data in your question will help. You can show the data by mocking up a table right here, or link to something like a Google spreadsheet, or in some way show examples of the data in a given row.

I was intrigued by the code so I changed it a bit to be more obvious what it is doing. This code does exactly what the OP's code does; no difference at all. Added some comments also.

Sub copiar()
    'Dim rng As Range
    Dim cell As Range
    'Dim rng2 As Range
    Dim cell2 As Range


    'active sheet
    'Set rng2 = ActiveSheet.Range("A2:A5")
    'rng2.Select

    'compare sheet
    Dim hojaSheet As Worksheet
    Set hojaSheet = Workbooks("perfumes.xlsx").Sheets("hoja")
    'Set rng = hojaSheet.Range("A4:A10")

    'source sheet
    Dim hoja1Sheet As Worksheet
    Set hoja1Sheet = Workbooks("perfumes.xlsx").Sheets("hoja 1")

    'compare each cell in range in the activeSheet
    For Each cell In ActiveSheet.Range("A2:A5").Cells
        'to each cell in range in hojaSheet
        For Each cell2 In hojaSheet.Range("A4:A10").Cells
            'if matching then copy from hoja 1 sheet to ActiveSheet
            If cell2 = cell Then
                Call hoja1Sheet.Range("K" & cell2.Row).Copy(ActiveSheet.Range("H" & cell.Row))
                Debug.Print "copy from: Hoja 1!" & "K" & cell2.Row & " > " & "copy to: ActiveSheet!" & "H" & cell.Row
            End If
        Next cell2
    Next cell

End Sub

Doesn't fix anything but may be useful if it helps clarify what the code is doing.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM