Question

I am writing a code to perform a formula on column "K", change its format and then copy and paste it in column "A".

I am also trying to copy and paste column "I" to column "B". "i" determines the numebr of cells in column B.

here is my code so far:

Sub Test()
   Dim i As Long
   i = Sheet1.Cells(Rows.Count, 2).End(xlUp).Row
   With Range("K3:K" & i)
        .Formula = "=DATE(A3,G3,H3)"
        .NumberFormat = "ddmmmyyyy"
        .Copy
        Range("A3:A" & i).PasteSpecial xlPasteFormats
   End With
   With Range("I3:I" & i)
        .Copy
        Range("B3:B" & i).PasteSpecial xlPasteFormats
   End With

End Sub

Any ideas where I went wrong? I am new to VBA so this is most likely a minor mistake I am overlooking.

Edit: The adjusted formula is copying Column I to Column B properly, but Column K to Column A is wrong.

Lets say column K has the dates:

29Apr1921
08May1922
21Oct1923

Column A now has:

04Apr1905
05Apr1905
06Apr1905
Was it helpful?

Solution

The issue is that it was missing paste values and was only pasting the format. It also needed its own With statement after the Date formula was performed.

Sub Test()
   Dim i As Long
   i = Sheet1.Cells(Rows.Count, 2).End(xlUp).Row
   With Range("K3:K" & i)
        .Formula = "=DATE(A3,G3,H3)"
        .NumberFormat = "ddmmmyyyy"
End With
   With Range("K3:K" & i)
   .Copy
    Range("A3:A" & i).PasteSpecial xlPasteValues
    Range("A3:A" & i).PasteSpecial xlPasteFormats
   End With

   With Range("I3:I" & i)
        .Copy
        Range("B3:B" & i).PasteSpecial

   End With

End Sub
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top