在VBA中迭代if语句

时间:2020-07-27 11:52:47

标签: excel vba loops

我是VB的新手,并且遇到了一些需要反复讨论的问题。下面是我的代码,我想多次遍历if语句。

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

1 个答案:

答案 0 :(得分:1)

您显然在代码中犯了一些菜鸟错误,让我先进行一些更正,然后从那里告诉我们您是否仍然有问题,如果有的话,请问哪些问题:

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