首页 > 解决方案 > 如果条件满足,Excel VBA 宏将复制数据

问题描述

这对我来说真的是高级的宏。如果有人可以提供帮助,我真的很感激!

  1. 我有如下数据。我想编写一个查找customerID的宏,例如:如果C2 = C3,那么我希望它使用D列查找上方或下方的行,向上或向下填充(ColumnA,ColumnB和ColumnD)基于关于数据是如何出来的。因为数据可能会出现,例如 A2 行将被清空或 A3 行将被清空,但每个客户最多只能拥有 2 行数据线。

标签: excelvba

解决方案


我会根据我的评论是否属实来回答。如果没有,以后可以更新。

我只是从我昨天给出的答案中获取了基础知识,并对其进行了修改以满足这个问题的条件。您应该能够看到差异以及更改它以执行此类任务的难易程度。

Sub AddMissingInfo()

Dim ws As Worksheet, lrow As Long, arr, i As Long, j As Long

Set ws = Sheets("Sheet1") 'Change to your sheet name
lrow = ws.Range("C" & ws.Rows.Count).End(xlUp).Row 'Use customerID to find last row, change column if needed
arr = ws.Range("A2:D" & lrow).Value 'Populate the array, change columns/starting row if needed

For i = 1 To UBound(arr, 1) - 1 'Stop loop at line before last (alas the -1)
    If arr(i, 3) = arr(i + 1, 3) Then 'Check if customer ID matches the row below
        If arr(i, 1) = "" Then 'Checks first name
            If arr(i + 1, 1) <> "" Then arr(i, 1) = arr(i + 1, 1)
        Else
            If arr(i + 1, 1) = "" Then arr(i + 1, 1) = arr(i, 1)
        End If
        If arr(i, 2) = "" Then 'Checks last name
            If arr(i + 1, 2) <> "" Then arr(i, 2) = arr(i + 1, 2)
        Else
            If arr(i + 1, 2) = "" Then arr(i + 1, 2) = arr(i, 2)
        End If
        If arr(i, 4) = "" Then 'Checks Order#
            If arr(i + 1, 4) <> "" Then arr(i, 4) = arr(i + 1, 4)
        Else
            If arr(i + 1, 4) = "" Then arr(i + 1, 4) = arr(i, 4)
        End If

    End If
Next i

ws.Range("A2:D" & lrow).Value = arr 'Dump the info back to the range. Change columns/starting row if needed

End Sub

推荐阅读