使用VBA比较Excel中的3列

我想使用VBA在Excel中比较2对1列

我已经使用这个代码实现了2到2列

Sub LIST1_LIST2() Dim list1 As Range Dim LIST2 As Range Set list1 = Range("B3:C181") Set LIST2 = Range("G3:H729") For Each row1 In list1.Rows For Each row2 In LIST2.Rows If (row1.Cells(1) = row2.Cells(1) And row1.Cells(2) = row2.Cells(2)) Then row1.Cells(1).Offset(0, 2) = row1.Cells(1) row1.Cells(2).Offset(0, 2) = row1.Cells(2) Exit For End If Next row2 Next row1 End Sub 

但是现在我需要一些VBA脚本,它可以像下面的图片一样工作 在这里输入图像说明

使用一个简单的Do Until Loop:

 Option Explicit Public Sub Example() Dim B As Range, _ C As Range, _ D As Range, _ F As Range, _ G As Range Dim i%, x% ' Dim as long Set B = Columns(2) Set C = Columns(3) Set D = Columns(4) Set F = Columns(6) Set G = Columns(7) i = 2 x = 2 Do Until IsEmpty(B.Cells(i)) Debug.Print B.Cells(i).Value & ", " & _ C.Cells(i).Value ' Print on Immed Win Do Until IsEmpty(F.Cells(x)) DoEvents ' For testing If F.Cells(x).Value = B.Cells(i).Value & ", " & _ C.Cells(i).Value Then Debug.Print F.Cells(i).Value = B.Cells(i).Value & ", " & _ C.Cells(i).Value ' Print on Immed Win G.Cells(x) = D.Cells(i) x = 2 ' Reset Loop Exit Do End If x = x + 1 Loop i = i + 1 Loop End Sub 

其他信息

DoEvents对于简单的事情是非常有用的,例如允许用户在启动后取消进程,例如search文件。 对于长时间运行的进程,通过使用Timer或将任务委托给ActiveX EXE组件,可以更好地实现处理器。在后一种情况下,任务可以完全独立于应用程序,操作系统可以处理多任务和时间分割。



Debug.Print Immediate Window用于debugging和计算expression式,执行语句,打印variables值等等。 它允许您在debugging过程中input要被开发语言评估或执行的expression式。 要显示“立即”窗口,请打开一个项目进行编辑,然后从“debugging”菜单中select“Windows”并select“立即”,或按CTRL + ALT + I。

你可以使用这个伪代码来指导你:

 If LASTNAME = Left(NAME,LASTNAME.Length) And _ FIRSTNAME = Right(NAME,FIRSTNAME.Length) Then