VBA Excel 2007:循环插入错误的位置行。

时间:2015-02-18 14:29:32

标签: excel vba excel-vba excel-2007

我编写了两个循环来比较2个列表,并将一个列表中的缺失信息插入到另一个列表中。 不幸的是,宏在运行时中间只插入第一行下面的行。我试图用If-Statement来避免这种情况,但是错误将从第2行开始。

以下是代码:

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

当我尝试

你能帮我改进代码吗?

2 个答案:

答案 0 :(得分:1)

替换

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

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

来自好伙伴MSDN的一点ActiveCell

  

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

答案 1 :(得分:1)

插入一行时,您不需要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