Vlookup多张表使用参考

时间:2017-03-20 14:05:06

标签: excel-vba vba excel

我有8张带有多列数据的纸张,我想要这些7张vlookup和sheet8以及所有7张纸张中的ID应该出现在所有7张纸张中应该删除剩余的行。

代码低于我所拥有的但是它不能正常工作我仍然可以看到数据中存在#N / A的ID。

Sub delete()

    Dim arr(), msg As String
    Dim c As Range
    Dim ws_lrow, ws8_lrow, i As Integer
    Dim ws As Worksheet

    ws8_lrow = Sheets("Sheet8").Cells(Rows.Count, 1).End(xlUp).Row

    ReDim arr(ws8_lrow)

    For i = 2 To ws8_lrow
        arr(i - 2) = Sheets("Sheet8").Cells(i, 1).Value
    Next i

    For Each ws In ActiveWorkbook.Sheets
        ws_lrow = ws.Cells(Rows.Count, 2).End(xlUp).Row

        For Each c In ws.Range("B2:B" & ws_lrow)
            If IsInArray(c, arr()) = 0 Then
                msg = msg & "User '" & c & "' from: " & ws.Name & vbCrLf
                c.EntireRow.delete xlShiftUp
            End If
        Next c
    Next ws

    MsgBox "The following users have been deleted:" & vbCrLf & msg

End Sub

Private Function IsInArray(valToBeFound As Variant, arr As Variant) As Boolean

    Dim element As Variant
    On Error GoTo IsInArrayError: 'array is empty
       For Each element In arr
            If element = valToBeFound Then
                IsInArray = True
                Exit Function
            End If
        Next element
    Exit Function

IsInArrayError:
    On Error GoTo 0
    IsInArray = False

End Function

1 个答案:

答案 0 :(得分:1)

在整个过程中迭代一系列行,自上而下和删除行时,您会遇到一个经典错误。在这种情况下,最简单和正确的方法是从下往上循环 。这个循环应该是固定的:

'For Each c In ws.Range("B2:B" & ws_lrow)
'    If IsInArray(c, arr()) = 0 Then
'        msg = msg & "User '" & c & "' from: " & ws.Name & vbCrLf
'        c.EntireRow.delete
'    End If
'Next c

从下往上循环:

For i = ws_lrow to 2 step -1
    If IsInArray(ws.Range("B" & i).value, arr) = 0 Then
        msg = msg & "User '" & ws.Range("B" & i).value & "' from: " & ws.Name & vbCrLf
        ws.Rows(i).delete
    End If
Next i