當列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'功能 –