Search code examples
excelvbaif-statementcopy-paste

If Statement will not copy the results to a seperate page


Creating an If statement, to sort out my data based on the month in a certain column. The code is as such

Worksheets("Project Info").Activate

Dim month As Long
Application.ScreenUpdating = False
For month = Cells(Rows.Count, 23).End(xlUp).Row To 1 Step -1
    If InStr(1, Cells(month, 23).Value Like "1/*", 1) _
    Then Cells(month, 23).EntireRow.Copy
    Worksheets("January").Activate
    ActiveSheet.Paste
Next month

For some reason, it won't copy data into the specified page. It doesn't even actually copy the data at all. Any ideas?


Solution

  • As mentioned in the comments above, you need to use sheet references otherwise you are going to jump back and forth between sheets and after the first iteration you are copying and pasting to the same sheet. You also have to specify where you are going to paste the data and change the destination each time, otherwise you will keep pasting over the same data.

    Dim ws1 as Worksheet
    Dim ws2 as Worksheet
    
    Set ws1 = Worksheets("Project Info")
    Set ws2 = Worksheets("January")
    
    Dim month As Long
    Dim t as Long
    
    Application.ScreenUpdating = False
    
    t=1
    For month = ws1.Cells(Rows.Count, 23).End(xlUp).Row To 1 Step -1
        If InStr(1, ws1.Cells(month, 23).Value Like "1/*", 1) Then
           ws1.Cells(month, 23).EntireRow.Copy
           ws2.Rows(t).PasteSpecial xlPasteAll
           t=t+1
        End if
    Next month