简体   繁体   中英

Making a VBA FOR loop using vlookup function in Excel

I would like to use a Vlookup function 47 times to get the value for every data. I call the table I am filling "Table 1". "Table 1 starts from E3. I would like to use the vlookup to find the value for cell E3 and fill it in F3.

I call the table from which I return value by Vlookup "Table2". "Table 2 is located in sheet "CC Name" and has two columns A and B.

I have tried two FOR Loops. One FOR Loop for the Vlookup function to be repeated 47 times. Second FOR Loop for the Name of the vlookup function "ccName" to use the function to fill the value in "Table 1" for 43 times, but I get error every time I implement the Code.

Sub GLcreation()

For n = 3 To 50
For c = 3 To 50

ccName(c) = WorksheetFunction.Vlookup(Range("E" & n), Worksheets("CC Name").Range("A:B"), 2, 0)

Range("F" & n) = ccName(c)

Next c
Next n

End Sub

If you can Show me how to Code the correct for Loop, I appreciate your help.

通过摆脱c循环,正确的代码是:

Range("F" & n) = WorksheetFunction.Vlookup(Range("E" & n), Worksheets("CC Name").Range("A:B"), 2, 0)

As soon as there is a non-match the code will fail. It's safer to test for match before making the lookup. Here is a better solution:

Sub GLcreation()

Dim n As Integer
Dim wf As WorksheetFunction
Set wf = WorksheetFunction

For n = 3 To 50
    If wf.CountIf(Worksheets("CC Name").Range("A:A"), Range("E" & n).Value) > 0 Then
        Range("F" & n).Value = wf.Index(Worksheets("CC Name").Range("B:B"), wf.Match(Range("E" & n).Value, Worksheets("CC Name").Range("A:A"), 0))
    End If
Next n

End Sub

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM