首页 文章

Excel VBA:从其他单元格复制并粘贴重复值

提问于
浏览
-1

我有一个包含两列的excel文件 . Excel截图如下:

enter image description here

我想要的是一个Excel VBA,它将读取所有重复值,如果它旁边的单元格为空白,则另一个重复帐户的值将粘贴在空白单元格中 . 预期结果:

enter image description here

我对Excel VBA不太满意,所以我非常感谢你的帮助 .

谢谢!

2 回答

  • 3

    你可以试试这个

    Sub Main()
        With Columns(1).SpecialCells(xlCellTypeConstants, XlTextValues).Offset(,1).SpecialCells(xlCellTypeBlanks)
            .FormulaR1C1 = "=R[-1]C"
            .Value = .Value
        End With
    End Sub
    

    哪里

    • 第一个SpecialCells选择具有一些文本值的A列单元格

    • 偏移量在右边的下一列中选择相应的单元格(即列B)

    • 第二个SpecialCells选择后一个范围内的空单元格

  • 2

    一个起点是遍历每个值并将其与列中的每个值进行比较:

    Sub FillDuplicates()
    Dim lastrow As Long
    
    lastrow = Cells(Rows.Count, "A").End(xlUp).Row 'find last row in column A
    
    For x = 1 To lastrow
        If Cells(x, 2).Value <> "" Then 'Check if cell in column B is empty
            For y = 1 To lastrow
                If Cells(y, 1).Value = Cells(x, 1).Value Then 'Compares cell against each value in column A
                    Cells(y, 2).Value = Cells(x, 2).Value 'If matches, add value in column B
                End If
            Next y
        End If
    Next x
    
    End Sub
    

相关问题