Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I am new to VBA...I want to copy a row from Sheet2 to Sheet1 if the first cell in this row says X and then do so for all the rows that meet this criteria. I have an error in the If condition...I don't know how to fix it.

Sub LastRowInOneColumn()
'Find the last used row in a Column: column A in this example
    Worksheets("Sheet2").Activate
    Dim LastRow As Long
    With ActiveSheet
        LastRow = .Cells(.Rows.Count, "A").End(xlUp).Row
    End With
    MsgBox (LastRow)
    For i = 1 To LastRow
    If Worksheet.Cells(i, 1).Value = "X" Then
    ActiveSheet.Row.Value.Copy _
    Destination:=Hoja1
    End If
    Next i
 End Sub
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
916 views
Welcome To Ask or Share your Answers For Others

1 Answer

You need to specify workseet. Change line

If Worksheet.Cells(i, 1).Value = "X" Then

to

If Worksheets("Sheet2").Cells(i, 1).Value = "X" Then

UPD:

Try to use following code (but it's not the best approach. As @SiddharthRout suggested, consider about using Autofilter):

Sub LastRowInOneColumn()
   Dim LastRow As Long
   Dim i As Long, j As Long

   'Find the last used row in a Column: column A in this example
   With Worksheets("Sheet2")
      LastRow = .Cells(.Rows.Count, "A").End(xlUp).Row
   End With

   MsgBox (LastRow)
   'first row number where you need to paste values in Sheet1'
   With Worksheets("Sheet1")
      j = .Cells(.Rows.Count, "A").End(xlUp).Row + 1
   End With 

   For i = 1 To LastRow
       With Worksheets("Sheet2")
           If .Cells(i, 1).Value = "X" Then
               .Rows(i).Copy Destination:=Worksheets("Sheet1").Range("A" & j)
               j = j + 1
           End If
       End With
   Next i
End Sub

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...