比较两个单元格A和D并复制重复数据

时间:2013-09-11 00:58:28

标签: excel-vba vba excel

如果A& D匹配,将A粘贴到G.然后添加B& E并将结果放在H列中。我有问题从B&添加值E进入H.

Private Sub CommandButton1_Click()
    Dim rng1 As Range
    Dim rng2 As Range
    Dim RowNo As Long
    Dim LR As Long

    Set rng1 = Worksheets("Sheet1").Range("D1:D100", Worksheets("Sheet1").Range("D" & Rows.Count).End(xlUp))
    Set rng2 = Worksheets("Sheet1").Range("A1:A100", Worksheets("Sheet1").Range("A" & Rows.Count).End(xlUp))

    For Each d In rng1
    LR = Range("H" & Rows.Count).End(xlUp).Row
    Range("F1:F" & LR).Formula = "=H1+C1"
        If Not d.Value = "" And Application.WorksheetFunction.CountIf(rng2, d) > 0 Then
            RowNo = Application.WorksheetFunction.Match(d, rng2)

            If d.Offset(, 1).Value = "" Then d.Offset(, 3).Resize(1).Value _
            = Worksheets("Sheet1").Range("A" & RowNo).Value

            If d.Offset(, 1).Value = "" Then d.Offset(, 4).Resize(1).Value _
            = Worksheets("Sheet1").Range("B" & RowNo).Value
        End If
    Next d
End Sub

示例单元格:

A   1           X   22      A 45
B   2           C   33      C 36
C   3           A   44      F 105
D   4           Y   55      
E   5           J   66      
F   6           O   77      
G   7           T   88      
                F   99      
                W   11      

1 个答案:

答案 0 :(得分:0)

如果问题只是将正确的数字输入H,请使用此代码。把它只是为了“结束Sub”。 代码假设您在A和D中填充的行数不会超过1000行,但您可以更改它。

Range("H1").Select
ActiveCell.FormulaR1C1 = _
    "=SUMIF(R1C1:R1000C1,RC[-1],R1C2:R1000C2)+SUMIF(R1C4:R1000C4,RC[-1],R1C5:R1000C5)"
Selection.Copy
Range("H2:H" & WorksheetFunction.CountA(Columns(7))).Select
ActiveSheet.Paste
Application.CutCopyMode = False
Range("H1:H" & WorksheetFunction.CountA(Columns(7))).Select
'the following lines are only necessary if you don't want a formula in H.
Selection.Copy
Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
    :=False, Transpose:=False
希望有所帮助! 最大