Excel宏不复制行

时间:2017-09-25 21:00:05

标签: excel vba excel-vba

我正在尝试创建一个比较2列的宏,每个列来自不同的文件,并将每个匹配项与其中一个文件中的一些其他单元格一起放入第三个文件中。

另外,在前两个文件中对它们进行了一些编辑,因此它们的实际数据单元格从它们各自列的第4行和第2行开始,所以我使用了2个不同的变量,所以我的循环将从这些单元格开始。

问题是,即使我的宏运行没有错误,它也不会将数据复制到第三个文件。

我有以下代码:

Sub Compare()
    Dim w1 As Worksheet, w2 As Worksheet, w3 As Worksheet
    Dim range1 As Range, range2 As Range

    Set w1 = Workbooks("Worksheet_Name1").Worksheets("Sheet1")
    Set w2 = Workbooks("Worksheet_Name2").Worksheets("Sheet2")
    Set w3 = Workbooks("Worksheet_Name3").Worksheets("Sheet3")

    Set range1 = w1.Range("E4", w1.Range("E" & Rows.Count).End(xlUp))
    Set range2 = w2.Range("A2", w2.Range("A" & Rows.Count).End(xlUp))

    For Each c In range2
        rangeVar2 = c
        If rangeVar2 > 3 Then
            For Each n In range1
                rangeVar1 = n
                If rangeVar > 2 Then
                    If w1.Cells(n, "E").Value = w2.Cells(c, "A").Value Then
                        w3.Cells(c, "A").Value = w1.Cells(c, "E").Value
                        w3.Cells(c, "B").Value = w2.Cells(c, "A").Value
                    End If
                End If
            Next n
        End If
    Next c
End Sub

1 个答案:

答案 0 :(得分:1)

好的,我为你重写了这个并改变了一些事情。这仍然可以稍微修改一下,但现在至少应该工作

rangeVar1rangeVar2完全是多余的,也阻止了您的代码运行(我认为)。不需要那些。

Sub ReWrite()
Dim w1 As Worksheet, w2 As Worksheet, w3 As Worksheet

Set w1 = Workbooks("Worksheet_Name1").Worksheets("Sheet1")
Set w2 = Workbooks("Worksheet_Name2").Worksheets("Sheet2")
Set w3 = Workbooks("Worksheet_Name3").Worksheets("Sheet3")

Dim lastrow1 As Long, lastrow2 As Long, i As Long, j As Long

lastrow1 = w1.Cells(w1.Rows.Count, "E").End(xlUp).Row
lastrow2 = w2.Cells(w2.Rows.Count, "A").End(xlUp).Row

For i = 4 To lastrow1
    For j = 2 To lastrow2
        If w1.Range("E" & i).Value = w2.Range("A" & j).Value Then
            w3.Range("A" & j).Value = w1.Range("E" & i).Value
            w3.Range("B" & j).Value = w2.Range("A" & j).Value
            End If
    Next j
Next i

End Sub