2014-01-12 51 views
5

我是VBA的新手......如果此行中的第一個單元格表示X,然後對滿足此條件的所有行執行此操作,我想從Sheet2複製一行到Sheet1標準。我在If條件中有錯誤...我不知道如何解決它。VBA將符合條件的行復制到另一張表

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 
+1

嘗試[自動填充](http://stackoverflow.com/questions/11631363/how-to-copy-a-line-in-excel-using-a-specific-word-and-pasting-to-another- excel -s) –

+1

我會如果我知道編程...我一直在學習VBA ...兩天了:)這是一種方式,我可以理解什麼是代碼... – Anca

回答

6

您需要指定workseet。改線

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

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

UPD:

嘗試使用下面的代碼(但它不是最好的方法作爲@SiddharthRout建議,考慮如何使用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 
+0

+ 1 as它回答了這個問題:)但絕對不是複製行的最佳方式,因爲它在循環中進行復制。正如我在上面的評論中提到的那樣,「Autofilter」是最好的選擇。 –

+0

謝謝,但現在我有一個新的錯誤後來在:ActiveSheet.Row.Value.Copy _ Destination:= Sheet1 ....它說,對象不承認這種規定或方法.. – Anca

+0

@SiddharthRout,I完全同意你的看法!在這種情況下,自動過濾器將是最好的。 –

0

格式化後如果您試圖將通過AutoFilter返回的值粘貼到單獨的工作表中,我發現了一種有效的方法來複制所有必需的數據。

With .Range("A1:A" & LastRow) 
    .Autofilter Field:=1, Criteria1:="=*" & strSearch & "*" 
    .Offset(1,0).SpecialCells(xlCellTypeVisible).Cells.Copy 
    Sheets("Sheet2").activate 
    DestinationRange.PasteSpecial 
End With 

在該塊中,AutoFilter發現所有包含的strSearch值的行和過濾掉所有其它的值。然後複製單元格(如果存在標題,則使用偏移量),打開目標工作表並將這些值粘貼到目標工作表上的指定範圍。

相關問題