excel - Transferring rows into another sheet
问题描述
I am trying to transfer two rows of Sheet1 (randomly and based on certain criteria) into Sheet3.
The values in cells "P2" and "P5" indicate the row number to be transferred, and column "A" has row numbers.
There's no possibility that values in "P2" and "P5" could match multiple rows in column "A". They should match 1 row each, so only one row should be copied per "P2" and "P5". Yet, sometimes I see multiple rows getting copied.
Below is the code:
Sub copyrows()
Dim tfRow As Range, cell As Object
Set tfRow = Range("A1:A") 'Range which includes the values
For Each cell In tfRow
If IsEmpty(cell) Then
Exit Sub
End If
If cell.Value = Range("P2").Value Then
cell.EntireRow.Copy
Sheet3.Select 'Target sheet
ActiveSheet.Range("A65536").End(xlUp).Select
Selection.Offset(1, 0).Select
ActiveSheet.Paste
End If
Next
End Sub
Sub copyrows2()
Dim tfRow2 As Range, cell As Object
Set tfRow2 = Range("A1:A") 'Range which includes the values
For Each cell In tfRow2
If IsEmpty(cell) Then
Exit Sub
End If
If cell.Value = Range("P5").Value Then
cell.EntireRow.Copy
Sheet3.Select 'Target sheet
ActiveSheet.Range("A65536").End(xlUp).Select
Selection.Offset(1, 0).Select
ActiveSheet.Paste
End If
Next
End Sub
解决方案
正如上面commnets中提到的@urdearboy,您需要在第二A
列范围内添加一行以避免出现错误。
要合并两个条件,在您的情况下添加一个Or
到您的If
.
为了更快地运行代码,不要Select
和Activate
不同的工作表,代码运行需要很长时间。相反,请使用一个Range
对象,例如CopyRng
,每次条件正常时,您都可以使用该函数if
将该单元格添加到范围中。在此处Union
阅读有关该功能的信息。Union
下面的代码注释中有更多注释。
修改后的代码
Option Explicit
Sub copyrows()
Dim Sht1 As Worksheet, Sht3 As Worksheet
Dim tfRow As Range, C As Range ' use Range not Object, also try not to use Cell it's close to Cells
Dim CopyRng As Range
Dim LastRow As Long
Set Sht1 = Sheet1
Set Sht3 = Sheet3
With Sht1
LastRow = .Cells(.Rows.Count, "A").End(xlUp).Row ' get last row with data in column A
Set tfRow = .Range("A1:A" & LastRow) 'Range which includes the values
For Each C In tfRow
If IsEmpty(C) Then
Exit Sub
End If
If C.Value = .Range("P2").Value Or C.Value = .Range("P5").Value Then ' use Or to combine both scenarios
If Not CopyRng Is Nothing Then
Set CopyRng = Application.Union(CopyRng, C) ' use Union to merge multiple ranges
Else
Set CopyRng = C
End If
End If
Next C
End With
' make sure there is at least one cells in your merged range
If Not CopyRng Is Nothing Then
' get last row with data in "sheet3"
LastRow = Sht3.Cells(Sht3.Rows.Count, "A").End(xlUp).Row
CopyRng.EntireRow.Copy Destination:=Sht3.Range("A" & LastRow + 1)
End If
End Sub
推荐阅读
- r - 如何在 R 中为这种情况编写循环?
- arrays - 使用已经排序的列表快速排序交换元素
- java - 如何将 2021-05-31T02:40:05.2Z 字符串转换为日期对象时区 (GMT+7) Java android
- scripting - 谷歌文档脚本,返回指定文本中间的文本值
- android - Instagram 应用程序如何在网格视图中显示他们的个人资料,并使用 Flutter 实现它
- python - 如何在 Python 中动态指定 unicode 字符串?
- apache-kafka - 由于组协调器重新发现不成功,Kafka 提交失败
- r - updatePickerInput 即时刷新更新
- r - 如何在 R 中使用 list.files() 读取包含高棉脚本(非 Windows 本机编码)的目录名称?
- android - 网站无法在安卓上正常运行