Sub NSV_LINK()
Dim cell As Range
Dim Rng As Range
Set Rng = Range(Range("A1"), Range("A" & Rows.Count).End(xlUp))
For Each cell In Rng
If cell.Value = "Hemanta" Then cell.EntireRow.Copy Sheets(2).Cells(1, 1)
Next cell
End Sub
在上面的代码中,我希望宏将值复制并粘贴到工作表2的连续行中。但是,我已经对目标单元格进行了硬编码,即,该值已粘贴到A1处。如何编写单元格目标,以便将值粘贴到连续的行中? Cells(i,1)...这样的事情。然后我的取值范围是1到20。如何用代码编写?
答案 0 :(得分:1)
您需要一个计数器,并且必须增加它
Sub NSV_LINK()
Dim cell As Range, Rng As Range, r As Long
Set Rng = Range(Range("A1"), Range("A" & Rows.Count).End(xlUp))
r = 1
For Each cell In Rng
If cell.Value = "Hemanta" Then
cell.EntireRow.Copy Sheets(2).Cells(r, 1)
r = r + 1
End If
Next cell
End Sub
答案 1 :(得分:1)
您可以采用与Set Rng = Range(Range("A1"), Range("A" & Rows.Count).End(xlUp))
中已经使用的相同技术来使目标范围动态化:
Sub NSV_LINK()
Dim cell As Range, Rng As Range
Set Rng = Range(Range("A1"), Range("A" & Rows.Count).End(xlUp))
For Each cell In Rng
If cell.Value = "Hemanta" Then cell.EntireRow.Copy Sheets(2).Cells(Rows.Count, 1).End(xlUp).Offset(1) ' make destination range dynamic to target sheeet column A first not empty cell after last not empty one
Next cell
End Sub