当列A和列B值匹配时,我想在Column D
中插入对应的Column C
值。使用VBA宏比较列
例如:
列A2等于列B2,现在列C2值是贴在柱D2
OR
柱A7等于列B3然后列C3的值过帐在列D3上
有关详细信息,请参阅屏幕快照,以便您了解我正在尝试做什么。
[请点击查看截图] [1]
我正努力的代码如下,但它不能正常工作,它只是给只有一个单元格的值:
Private Sub ForComparing_Click()
Dim ws As Worksheet
Dim cel As Range
Dim lastRowA As Long, lastRowB As Long, lastRowC As Long
Set ws = ThisWorkbook.Sheets("Sheet1")
With ws
lastRowA = .Cells(.Rows.Count, "A").End(xlUp).Row 'last row of column A
lastRowB = .Cells(.Rows.Count, "B").End(xlUp).Row 'last row of column B
lastRowC = .Cells(.Rows.Count, "C").End(xlUp).Row 'last row of column C
For Each cel In .Range("A2:A" & lastRowA) 'loop through column A
'check if cell in column A exists in column B
If WorksheetFunction.CountIf(.Range("B2:B" & lastRowB), cel) = 0 Then
.Range("D" & cel.Row) = "No Match"
Else
.Range("D" & cel.Row) = .Range("C" & cel.Row)
End If
Next
End With
End Sub
被修改1:
请参考下面这个代码的输出: Click here to see screen shot
Column A3
应Column B5
比较,因为价值D
在这种情况下相等,那么它应该打印Column C5
值Column D3
此外,它应该给价值Column D
为Column A
每个值,但后前4个值停止。
谢谢你的时间。
编辑2:
你刚才编辑什么是完全正确的,但我想每个Column A
值做到这一点。
我想比较每个Column A
的值与Column B
,然后相应的Column C
值被复制到Column D
。
向我们展示你已经尝试过的代码,并解释了问题的所在。请记住,您可以录制一个宏让您开始。 – braX
阅读关于'Match'功能 –