user3875524
user3875524

Reputation: 11

Iterate if statement in vba

I am new to VB and facing some issues to iterate through. below is my code and i want to iterate the if statement more than once.

Sub Refresh_Data()

On Error Resume Next
A = Worksheets("DATA").Cells(Rows.Count, 4).End(xlUp).Row
    Dim x As String
     
        x = 9550
   For i = 1 To A
   
   If Worksheets("DATA").Cells(i, 1).Value = x Then
      
        Worksheets("DATA").Rows(i).Copy 
        Worksheets(x).Activate 
        B = Worksheets(x).Cells(Rows.Count, 4).End(xlUp).Row 
        Worksheets(x).Cells(B + 1, 1).Select 
        ActiveSheet.Paste  
        Worksheets("DATA").Activate 
        x = x + 50

    End If
 Next
Application.CutCopyMode = False

ThisWorkbook.Worksheets("DATA").Cells(1, 1).Select

End Sub

Upvotes: 0

Views: 35

Answers (1)

Dominique
Dominique

Reputation: 17493

You are clearly making some rookie mistakes in your code, let me make some first corrections, and from there please tell us if you still have problems and in case yes, which ones:

Sub Refresh_Data()

' On Error Resume Next (do not use this, it is masking errors instead of solving them)
Dim A As Long
Dim B As Long ' not only A, also B
Dim x As Long ' x is not a string, but a number
Dim i As Long ' you forgot about i

A = Worksheets("DATA").Cells(Rows.Count, 4).End(xlUp).Row
     
x = 9550
For i = 1 To A
   
  If Worksheets("DATA").Cells(i, 1).Value = x Then
      
    Worksheets("DATA").Rows(i).Copy
    Worksheets(x).Activate
    B = Worksheets(x).Cells(Rows.Count, 4).End(xlUp).Row
    Worksheets(x).Cells(B + 1, 1).Paste ' you can paste here directly, no reason to select first.
    Worksheets("DATA").Activate
    x = x + 50

  End If
Next
Application.CutCopyMode = False

ThisWorkbook.Worksheets("DATA").Cells(1, 1).Select

End Sub

Upvotes: 1

Related Questions