[英]How to copy row to another sheet if the cell value of C matches the sheetname
So I pull data then I have to copy and paste the rows to their respective sheets basing on the value of Column D. I have a code that does the thing but it takes too slow when there are thousands of rows. 因此,我提取数据,然后必须根据D列的值将行复制并粘贴到各自的工作表中。我有一个代码可以执行此操作,但是当成千上万行时,它的处理速度太慢。
Sub COPY_DATA()
Dim bottomD As Long
bottomD = Range("D" & Rows.Count).End(xlUp).Row
Dim c As Range
Dim ws As Worksheet
For Each c In Sheets("Data").Range("D2:D" & bottomD)
For Each ws In Sheets
ws.Activate
If ws.Name = c And ws.Name <> "Userform" Then
c.EntireRow.copy Cells(Rows.Count, "A").End(xlUp).Offset(1, 0)
End If
Next ws
Next c
Worksheets("Data").Activate
End Sub
I want to make the process of copy and pasting faster 我想使复制和粘贴过程更快
This should be faster: 这应该更快:
Sub COPY_DATA()
Dim dict As Object
Dim bottomD As Long
Dim c As Range
Dim ws As Worksheet,wb as workbook, wsData as Worksheet
Set wb = ActiveWorkbook
Set wsData = wb.worksheets("Data")
'collect the sheet names
Set dict = CreateObject("scripting.dictionary")
For Each ws In wb.Worksheets
If ws.Name <> "Userform" Then dict.Add ws.Name, True
Next ws
Application.ScreenUpdating = False
bottomD = wsData.Range("D" & Rows.Count).End(xlUp).Row
For Each c In wsData.Range("D2:D" & bottomD)
If dict.exists(c.Value) Then
c.EntireRow.Copy wb.Worksheets(c.Value).Cells(Rows.Count, "A").End(xlUp).Offset(1, 0)
End If
Next c
Application.ScreenUpdating = True
wsData.Activate
End Sub
Stop .Activating
! 停止。
.Activating
! Totally unnecessary and updating the UI is taking time. 完全不必要,更新UI需要花费时间。 Make sure all calls to ranges are qualified.
确保对范围的所有调用均合格。
Option Explicit '<--- Always at the top of modules!
Sub COPY_DATA()
Dim bottomD As Long
bottomD = Range("D" & Rows.Count).End(xlUp).Row
Dim c As Range
Dim ws As Worksheet
For Each c In Sheets("Data").Range("D2:D" & bottomD)
For Each ws In Sheets
With ws
If .Name = c.Value And .Name <> "Userform" Then
c.EntireRow.copy Cells(.Rows.Count, "A").End(xlUp).Offset(1, 0)
End If
End With
Next ws
Next c
End Sub
Note also that I explicitly stated c.Value
instead of using the implicit/default property (which just happens to be Value). 还要注意,我明确声明了
c.Value
而不是使用隐式/默认属性(恰好是Value)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.