VBA Excel 2007:循环插入错误的地方行上。

我写了两个循环来比较两个列表,并从一个列表中插入缺less的信息到另一个列表中。 不幸的是,这个macros在运行时只插入了第一行以下的行。 我试图用If语句来避免这种情况,但是这个错误会在第二行开始。

这里是代码:

Sub CopyData() Dim dl_length As Integer Dim oa_length As Integer Dim dl_count As Integer Dim oa_count As Integer dl_length = Worksheets("download").Cells(Rows.Count, 1).End(xlUp).Row + 1 oa_length = Worksheets("overall").Cells(Rows.Count, 1).End(xlUp).Row + 1 For dl_count = 1 To dl_length For oa_count = 1 To oa_length If Worksheets("download").Range("F" & dl_count) = Worksheets("overall").Range("C" & oa_count) Then Worksheets("overall").Range("C" & oa_count).Select ActiveCell.Offset(1).EntireRow.Insert Worksheets("overall").Range("A" & oa_count + 1) = "Search and replace" Worksheets("overall").Range("E" & oa_count + 1) = Worksheets("download").Range("L" & dl_count) End If oa_length = Worksheets("overall").Cells(Rows.Count, 1).End(xlUp).Row + 1 Next oa_count Next dl_count End Sub 

当我尝试

你能帮我改进代码吗?

当插入一行时,您不需要oa_length = Worksheets("overall").Cells(Rows.Count, 1).End(xlUp).Row + 1

相反, oa_length = oa_length + 1会更快。

也应该在End if之前。

但仍然更新oa_length不会使For循环更进一步。

您必须使用Whilerepeat until循环为此目的。

 Option Explicit Sub CopyData() Dim dl_length& Dim oa_length& Dim dl_count& Dim oa_count& Dim Sh_oa As Worksheet Dim Sh_dl As Worksheet With ThisWorkbook Set Sh_oa = .Sheets("overall") Set Sh_dl = .Sheets("download") End With With Sh_oa oa_length = .Cells(.Rows.Count, 1).End(xlUp).Row 'i removed the +1, wich is a blank cell End With With Sh_dl dl_length = .Cells(.Rows.Count, 1).End(xlUp).Row End With With Application 'this part is to make things faster... .ScreenUpdating = False .EnableEvents = False .Calculation = xlCalculationManual End With For dl_count = 1 To dl_length While oa_count <= oa_length oa_count = oa_count + 1 If Sh_dl.Range("F" & dl_count).Value2 = Sh_oa.Range("C" & oa_count).Value2 Then oa_count = oa_count + 1 'if you insert a line, you'll need to read a line after that later With Sh_oa .Rows(oa_count).Insert .Cells(oa_count, 1).Value2 = "Search and replace" .Range("E" & oa_count).Value2 = Sh_dl.Range("L" & dl_count).Value2 End With oa_length = oa_length + 1 'wider the scope of checks End If Wend Next dl_count Set Sh_oa = Nothing Set Sh_dl = Nothing With Application .ScreenUpdating = True .EnableEvents = True .Calculation = xlCalculationAutomatic End With End Sub 

更换

  Worksheets("overall").Range("C" & oa_count).Select ActiveCell.Offset(1).EntireRow.Insert 

 With Worksheets("overall").Range("C" & oa_count).Offset(1,0).EntireRow.Insert 

关于从好家伙的ActiveCell一点MSDN:

返回一个Range对象,表示活动窗口(顶部的窗口)或指定窗口中的活动单元格。 如果该窗口不显示工作表,则此属性失败。 只读。