|
这样吗?
- Sub ExtractMatchingNumbersBetweenRows()
- Dim ws As Worksheet
- Dim sourceRange As Range
- Dim destCell As Range
- Dim i As Long, j As Long, k As Long
- Dim lastRow As Long
- Dim matchCount As Long
-
- ' 设置要操作的工作表
- Set ws = ThisWorkbook.Sheets("Sheet1") ' 请根据需要修改工作表名称
-
- ' 设置源范围和目标范围
- Set sourceRange = ws.Range("B2:U8") ' 请根据需要修改源范围
- Set destCell = ws.Range("W2") ' 请根据需要修改目标范围起点
-
- ' 清除目标范围的旧数据
- ws.Range(destCell, destCell.Offset(sourceRange.Rows.Count - 1, sourceRange.Columns.Count - 1)).ClearContents
-
- ' 获取源范围的最后一行
- lastRow = sourceRange.Rows.Count
-
- ' 从第二行开始遍历每一行数据,与上一行进行比较
- For i = 2 To lastRow
- matchCount = 0
-
- ' 遍历上一行的每个数字
- For j = 1 To sourceRange.Columns.Count
- ' 遍历当前行的每个数字
- For k = 1 To sourceRange.Columns.Count
- If sourceRange.Cells(i, k).Value = sourceRange.Cells(i - 1, j).Value Then
- ' 如果找到相同的数字,将其写入目标范围,避免重复写入
- If Not IsEmpty(sourceRange.Cells(i, k).Value) Then
- destCell.Cells(i, matchCount + 1).Value = sourceRange.Cells(i, k).Value
- matchCount = matchCount + 1
- End If
- End If
- Next k
- Next j
- Next i
-
- MsgBox "提取完成!"
- End Sub
复制代码
|
|