[英]VBA copy rows that meet criteria to another sheet
我是VBA的新手...如果此行中的第一個單元格表示X,則我要將Sheet2中的一行復制到Sheet1,然后對符合此條件的所有行執行此操作。 我在If條件中有錯誤...我不知道如何解決它。
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
您需要指定工作集。 改變線
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
格式化我自己代碼的上一個答案后,如果您嘗試將通過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
值的所有行,並過濾掉所有其他值。 然后復制單元格(如果有標題,則使用偏移量),打開目標工作表並將值粘貼到目標工作表上的指定范圍。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.