VBA for循环与VLookups避免重复

时间:2016-01-20 16:08:30

标签: excel vba excel-vba

我正在编制一份员工CPD课程列表和他们的工作时间,主要为每个人制作打印输出。我从多个工作表中提取数据,并且我在使用VLOOKUP时不断找到相同的数据。我的代码目前是:

    result = lookup.Find(name) Is Nothing

    If (result = False) Then
        For Each cell In lookup
            className = Application.VLookup(name, lookup, 7, True)
            classHours = Application.VLookup(name, lookup, 9, True)
            Sheets("employee output").Range("B" & counter).Formula = className
            Sheets("employee output").Range("C" & counter).Formula = classHours
            empHours = empHours + classHours
            counter = counter + 1
            numClasses = numClasses + 1
            corporate = Range("B" & i)  *** vba precompliles the loop so this doesn't work *
            Set lookup = Range("corporate:K") ** doesn't work either***
        Next
        End If

所以我需要限制查找范围的范围或以某种方式避免查找相同的数据。任何帮助将不胜感激......

1 个答案:

答案 0 :(得分:0)

I assume your lookup variable represents the range containing you data.

Your data duplication propably comes from your for each loop. Indeed, you are iterating trough each Cell of your range. That means that once the name is found, the code Inside the loop is executed as many times as there are cells in the range lookup.

Try changing your loop to the following:

Dim row as Range

for each row In lookup.Row
    'your code goes here
Next

Whit this, the code will only run once for each rows.