Sub
ExtractMatchingValues()
Dim ws As Worksheet
Dim lastRow As Long
Dim i As Long
Dim dict As Object
Dim col1 As Range, col2 As Range
Dim resultCol As Range
Dim value As Variant
Set ws = ThisWorkbook.Sheets(
"Sheet1"
) ' 修改为你要操作的工作表名称
lastRow = ws.Cells(ws.Rows.Count,
"A"
).
End
(xlUp).Row ' 假设数据从第一列开始,可以根据实际情况修改
' 将两列存放到 Range 对象中
Set col1 = ws.Range(
"A1:A"
& lastRow) ' 第一列的范围
Set col2 = ws.Range(
"B1:B"
& lastRow) ' 第二列的范围
' 创建一个字典用于存放相同的数值
Set dict = CreateObject(
"Scripting.Dictionary"
)
' 创建一个新列来存放结果
Set resultCol = ws.Cells(1, 3) ' 放到第三列,可以根据实际情况修改
' 遍历第一列,将值存放到字典中
For
i = 1 To lastRow
dict(col1.Cells(i, 1).Value) = True
Next i
' 遍历第二列,如果值在字典中存在,则写入到新列中
For
i = 1 To lastRow
If
dict.Exists(col2.Cells(i, 1).Value) Then
resultCol.Cells(i, 1).Value = col2.Cells(i, 1).Value
End
If
Next i
' 释放对象
Set dict =
Nothing
Set resultCol =
Nothing
Set col1 =
Nothing
Set col2 =
Nothing
Set ws =
Nothing
End
Sub