【发布时间】:2017-09-26 14:25:51
【问题描述】:
我正在尝试创建一个宏来比较 2 列,每一列来自不同的文件,并将每个匹配项连同其中一个文件中的一些其他单元格一起放入第三个文件中。
另外,在前 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
【问题讨论】:
-
代码对我来说看起来不错,虽然我更喜欢
For i = 1 to lastrow循环而不是遍历预设范围,但我认为它提供了更多的可读性。但是,我会说,您的代码的某些部分是多余的 - 当您的范围已预设时,为什么需要rangeVar2和rangeVar1?那些不会总是评估为True? -
在
If w1.Cells(n, "E").Value = w2.Cells(c, "A").Value上方添加一个MsgBox,用于比较值并手动检查:MsgBox "Comparing " & w1.Cells(n, "E").Value & " and " & w2.Cells(c, "A").Value & "..."