I'm trying to code a macro to copy specific values from a worksheet to another. When I run the code it works just fine, but if I run it, it doesn't.
The idea is to copy all the lines from one workbook to a new one but only some of the cells from two lines at a time. I made a macro with some trivial validations, and then call a function to make the copying. (The function can be called with "espaciosEnBlanco" being 0 or having a positive value, and the columnaValorTotal can be two different columns)
The parameters are:
originWorksheet: original workbook
newWorksheet: destiny workbook
valueColumn: the column from where I need one of the values
iFirstRow: index (starts in 0)
blankRows: index to leave blank rows (When you're calling the function and you don't need to leave empty rows, you send 0 in this fild)
iWithoutTitle: another index (starts in 2 and increments by 1 each iteration)
nextRowsNeedBlankSpaces: boolean that indicates the you need to leave blank rows
I tried to replicate them in many ways; copying them, matching the values, changing Cells to Range, and matching the values with Range. I also try importing Sleep function and putting it between all lines, and the same with wait, just in case it wasn't having enough time to copy the values, but it didn't work either.
What I can't understand is that when I debug it line by line it works just fine.
Public Function CopiarRegistros(originWorksheet, newWorksheet, valueColumn, iFirstRow, blankRows, iWithoutTitle, nextRowsNeedBlankSpaces)
If (Cells((iWithoutTitle + iFirstRow), valueColumn).Value < 0) Then
originWorksheet.Cells((iWithoutTitle + iFirstRow), "T").Copy Destination:=newWorksheet.Cells((iWithoutTitle - 1 + iFirstRow + blankRows), "B")
originWorksheet.Cells((iWithoutTitle + 1 + iFirstRow), "T").Copy Destination:=newWorksheet.Cells((iWithoutTitle + 1 - 1 + iFirstRow + blankRows), "B")
originWorksheet.Cells((iWithoutTitle + 1 + iFirstRow), valueColumn).Copy Destination:=newWorksheet.Cells((iWithoutTitle - 1 + iFirstRow + blankRows), "K")
newWorksheet.Range("I" & (iWithoutTitle - 1 + iFirstRow + blankRows)).Value = "D"
newWorksheet.Range("I" & (iWithoutTitle + 1 - 1 + iFirstRow + blankRows)).Value = "C"
Else
originWorksheet.Cells((iWithoutTitle + iFirstRow), "T").Copy Destination:=newWorksheet.Cells((iWithoutTitle - 1 + iFirstRow + blankRows), "B")
originWorksheet.Cells((iWithoutTitle + 1 + iFirstRow), "T").Copy Destination:=newWorksheet.Cells((iWithoutTitle + 1 - 1 + iFirstRow + blankRows), "B")
originWorksheet.Cells((iWithoutTitle + 1 + iFirstRow), valueColumn).Copy Destination:=newWorksheet.Cells((iWithoutTitle - 1 + iFirstRow + blankRows), "K")
newWorksheet.Range("I" & (iWithoutTitle - 1 + iFirstRow + blankRows)).Value = "C"
newWorksheet.Range("I" & (iWithoutTitle + 1 - 1 + iFirstRow + blankRows)).Value = "D"
End If
iFirstRow = iFirstRow + 1
If (nextRowsNeedBlankSpaces) Then
blankRows = blankRows + 2
End If
End Function