【发布时间】:2016-12-08 14:37:43
【问题描述】:
我有两个名为“Source1”和“Source2”的工作簿。
对于“Source1”最后一列中的每个单元格,我检查它是否存在于“Source2”最后一列中。
如果是,那么我会根据一些标准从该行中复制 4 个单独的单元格到一个名为“Target”的新工作簿中。
我的宏正在运行,但由于我有数千个单元格要循环,因此我至少需要 10 分钟才能完成宏。我一天要运行很多次,所以我想优化我的代码,这样它会花费更少的时间。
这是我的代码
Sub Loop_Cells()
Application.ScreenUpdating = False
Application.DisplayAlerts = False
Application.SheetsInNewWorkbook = 1
Dim Source, Source2, Target As Workbook
Dim c As Range
Dim lRow, lRow2 As Long
Dim x, y, w As Integer
Set Source = Workbooks.Open("C:\Reports\Source1.xlsx")
Source.Activate
x = ActiveSheet.UsedRange.Columns.Count
ActiveSheet.Cells(1, x + 1) = "Concate"
lRow = ActiveSheet.Range("A" & Rows.Count).End(xlUp).Row
For i = 2 To lRow
ActiveSheet.Cells(i, x + 1).Value = ActiveSheet.Cells(i, 6).Value & ActiveSheet.Cells(i, 7).Value
Next i
ActiveSheet.Columns(x + 1).NumberFormat = "0"
Set Source2 = Workbooks.Open("C:\Reports\Source2.xlsx")
Source2.Activate
y = ActiveSheet.UsedRange.Columns.Count
ActiveSheet.Cells(1, y + 1) = "Concate"
lRow2 = ActiveSheet.Range("A" & Rows.Count).End(xlUp).Row
For i = 2 To lRow2
ActiveSheet.Cells(i, y + 1).Value = ActiveSheet.Cells(i, 48).Value & ActiveSheet.Cells(i, 3).Value
Next i
ActiveSheet.Columns(y + 1).NumberFormat = "0"
Set Target = Workbooks.Add
Target.Sheets(1).Name = "ExistCells"
Source.Sheets(1).Activate
w = 1
For Each c In Source1.Sheets(1).UsedRange.Columns(x + 1).Cells
For j = 2 To lRow2
If c.Value = Source2.Sheets(1).Cells(j, y + 1).Value Then
Target.Sheets(1).Cells(w, 1).Value = Source2.Sheets(1).Cells(j, 48).Value
Target.Sheets(1).Cells(w, 2).Value = Source2.Sheets(1).Cells(j, 3).Value
Target.Sheets(1).Cells(w, 3).Value = Source2.Sheets(1).Cells(j, 27).Value
Target.Sheets(1).Cells(w, 4).Value = Source2.Sheets(1).Cells(j, 41).Value
w = w + 1
End If
Next j
Next c
Workbooks("Source1.xlsx").Close SaveChanges:=False
Workbooks("Source1.xlsx").Close SaveChanges:=False
Target.Activate
ActiveWorkbook.SaveAs FileName:= "C:\Reports\Target.xlsx", _
FileFormat:=xlOpenXMLWorkbook, CreateBackup:=False
Application.ScreenUpdating = True
Application.DisplayAlerts = True
End Sub
我认为问题出在这部分,当单元格存在时,我不需要循环到最后一行,我应该移动到下一行。
对于 j = 2 到 lRow2
如果 c.Value = Source2.Sheets(1).Cells(j, y + 1).Value 那么 ...
任何建议如何调整我的代码?
【问题讨论】:
-
获取行数并使用
For循环而不是For Each循环? -
对于正在运行但需要改进的代码(如本例),Code Review 可能是更好的选择。
-
你没有正确声明你的变量......除非你的意思是 Source、lRow、x & y 是 Variants。每个变量都必须设置为数据类型...所以 Dim x As Integer, y As Integer, w As Integer....