【发布时间】:2018-09-17 08:39:52
【问题描述】:
我需要将相关行复制到新的 Excel 工作表。代码将遍历原始工作表中的每一行,并根据数组中指定的相关国家和产品选择行到第二个工作表中。
Private Sub CommandButton1_Click()
a = Worksheets("worksheet1").Cells(Rows.Count, 2).End(xlUp).Row
Dim countryArray(1 To 17) As Variant
Dim productArray(1 To 17) As Variant
' countryArray(1)= "Australia" and so on...
' productArray(1)= "Product A" and so on...
Application.ScreenUpdating = False
Application.Calculation = xlCalculationManual
For i = 3 To a
For Each j In countryArray
For Each k In productArray
Sheets("worksheet1").Rows(i).Copy Destination:=Sheets("worksheet2").Range("A" & Rows.Count).End(xlUp).Offset(1)
Next
Next
Next
Application.CutCopyMode = False
Application.ScreenUpdating = False
End Sub
每次我运行代码时,电子表格都会在几分钟内停止响应。如果有人可以帮助我,将不胜感激,在此先感谢!
【问题讨论】:
-
你希望 Application.ScreenUpdating = True 在最后切换回重绘。
-
我还会添加
Application.Calculation = xlCalculationManual和Application.EnableEvents = False以加快速度。不要忘记在代码末尾反转它。 -
//define countryArray 和 productArray 不是您在 VBA 中的评论方式。使用'
-
countryArray 或 productArray 中没有值,为什么要循环它们??
-
根据您尚未共享的信息,您将通过以下方式之一大大加快此速度:
1将整个表读入 VBA 数组;遍历将相关行提取到字典/集合的数组;将结果写入results数组并将其写回新工作表。2使用过滤器并使用.SpecialCells(xlvisible)属性复制到新工作表。3使用允许一次复制的高级过滤器;但需要在工作表中写入Criteria Array。
标签: excel vba copy-paste