[英]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. 我想使用Vlookup函数47次来获取每个数据的值。 I call the table I am filling "Table 1".
我将要填充的表称为“表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.
“表1从E3开始。我想使用vlookup查找单元格E3的值并将其填写在F3中。
I call the table from which I return value by Vlookup "Table2". 我将通过Vlookup从中返回值的表称为“ Table2”。 "Table 2 is located in sheet "CC Name" and has two columns A and B.
“表2位于工作表“ CC名称”中,并具有两列A和B。
I have tried two FOR Loops. 我已经尝试了两个FOR循环。 One FOR Loop for the Vlookup function to be repeated 47 times.
V FORUPUP函数的一个FOR循环重复47次。 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.
vlookup函数“ ccName”的名称的第二个FOR循环使用该函数填充“表1”中的值达43次,但是每次实现该代码时都会出错。
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.