VBA计数两次循环?

时间:2015-08-05 14:23:53

标签: excel vba excel-vba loops repeat

所以我的代码会查看列I:L中的名称,如果条目与名称匹配,则会将该行列A的值粘贴到另一个工作表中。但是,如果名称在I:L中的同一行中出现两次,则它会将列A中的值粘贴两次。我该如何解决这个问题,以便只有在发生这种情况时才会粘贴一次A列? 谢谢!

Private Sub Worksheet_Change(ByVal Target As Range)Dim r As Range, Vin As Variant, Vout As Variant, i As Long, j As Long, ct As Long, S As Long
Set Target = Target(1)
If Not Intersect(Range("M3"), Target) Is Nothing Then
    Application.EnableEvents = False
    Set r = Range("I14:I59")
    r.ClearContents
    With Sheets("Master List").Range("I2:L1000" & Sheets("Master List").Cells(Rows.Count, 1).End(xlUp).Row)
        Vin = .Value
        ReDim Vout(1 To UBound(Vin, 1))
        For i = 1 To UBound(Vin, 1)
            For j = 1 To UBound(Vin, 2)
                If Vin(i, j) = Target.Value Then
                    ct = ct + 1
                     S = i + 1
                    Vout(ct) = Sheets("Master List").Range("A" & S).Value
                End If
            Next j
        Next i
    End With
    If ct > 0 Then
        ReDim Preserve Vout(1 To ct)
        r.Resize(ct).Value = Application.Transpose(Vout)
    End If
    Application.EnableEvents = True
End If
End Sub

1 个答案:

答案 0 :(得分:0)

只要您一次只查找一个名称,就可以在找到行计数器i后立即增加它:

If Vin(i, j) = Target.Value Then
    ct = ct + 1
    S = i + 1
    Vout(ct) = Sheets("Master List").Range("A" & S).Value
    i = i + 1
End If