首页 > 解决方案 > 有没有办法在 Excel 列中添加与不匹配数据计数相对应的行?

问题描述

我在一个工作簿中有两个列表,对应的数据格式不一致。

当我在一列中遇到不匹配时,我需要添加行(与存在重复的次数一样多,仅在工作表的一部分中,然后复制并粘贴该数据直到下一个项目。

我正在尝试做的事情。
在此处输入图像描述

标签: excelvbaexcel-formula

解决方案


向下扫描工作表并记住 col E 匹配的最后一行以填充缺失值。

Option Explicit
Sub align()

    Dim wb As Workbook, ws As Worksheet
    Dim cell As Range
    Dim iLastRow As Long, iRowE As Long, iRowMatch As Long

    Set wb = ThisWorkbook
    Set ws = wb.Sheets("Sheet1")
    iLastRow = ws.Range("A" & Rows.Count).End(xlUp).Row

    iRowE = 3
    For Each cell In ws.Range("A3:A" & iLastRow)
        'Debug.Print cell.Address

        ' copy unchanged
        cell.Resize(1, 3).Copy cell.Offset(0, 10) ' ABC to KLM
        cell.Copy cell.Offset(0, 14) ' A to 0
        cell.Offset(0, 1).Resize(1, 2).Copy cell.Offset(0, 16) 'BC to QR

        If ws.Cells(iRowE, "E") = cell.Value Then
           iRowMatch = iRowE
           iRowE = iRowE + 1
        End If

        ' copy matched row
        If iRowMatch > 0 Then
           ws.Cells(iRowMatch, "F").Copy cell.Offset(0, 15) ' F to P
        Else
           MsgBox "No initial match for " & cell.Value, vbCritical
        End If
    Next
    MsgBox "Done"
End Sub


推荐阅读