简体   繁体   English

在宏函数中使用Vlookup

[英]Using Vlookup in a macro function

I need to use Vlookup macro =VLOOKUP(E2,[gpic.xlsx]Sheet1!$A:$D,4,FALSE) for every cell until it ends. 我需要为每个单元格使用Vlookup宏= VLOOKUP(E2,[gpic.xlsx] Sheet1!$ A:$ D,4,FALSE)直到结束。 I'm not sure how to use long instead of range. 我不确定如何使用long而不是range。 When I use range it sometimes goes over because I predict wrong and I want everything to be automated, can anyone help please? 当我使用范围时,有时会因为预测错误而结束,并且我希望一切都自动化,有人可以帮忙吗? instead of the E2 I need it to go through all of them but I want to incorporate it into my macro. 而不是E2,我需要它来遍历所有这些,但是我想将其合并到我的宏中。

Sub Work()
Dim LR As Long
Dim row As String
row = "E2"
row = "E" & x
LR = Range("E" & Rows.Count).End(xlUp).row
Range(Columns(6), Columns(7)).Select
For x = 0 To 2
row = "E" & x
Range("F2:F" & LR).Formula = "=VLOOKUP(" & row & ",[gpic.xlsx]Sheet1!$A:$D,4,FALSE)"
Next




End Sub

To expand on what JDuarteDJ said, using a variable to loop through the rows would likely work best. 为了扩展JDuarteDJ所说的内容,使用变量循环遍历行可能会最好。 However, you mentioned sometimes you predict the number of rows incorrectly. 但是,您提到有时您会错误地预测行数。 You could use: 您可以使用:

rowCount = ActiveSheet.Range("F" & Rows.Count).End(xlUp).Row rowCount = ActiveSheet.Range(“ F”&Rows.Count).End(xlUp).Row

This will give you the count of the rows with somthing in them in column F. Then you can do the same loop that JDuarteDJ mentioned only instead of 这将为您提供F列中包含某些内容的行数。然后,您可以执行JDuarteDJ仅提及而不是提及的相同循环

x = 2 to 20 x = 2至20

You could use 你可以用

For x = 2 to rowCount 对于x = 2到rowCount
' Do all things previously mentioned and whatver you need to do '做前面提到的所有事情以及您需要做什么
Next 下一个

Hope this helps 希望这可以帮助

-------------UPDATE--------------------------- ------------- UPDATE ---------------------------
The problem with the edit, I THINK, is that within your for loop, you're using: 我认为编辑的问题是在for循环中,您正在使用:

Range("F2:F" & LR).FormulaR1C1 = "=VLOOKUP(&row&,[gpic.xlsx]Sheet1!$A:$D,4,FALSE)" Range(“ F2:F”&LR).FormulaR1C1 =“ = VLOOKUP(&row&,[gpic.xlsx] Sheet1!$ A:$ D,4,FALSE)”

Which is isn't iterating through the correct number of times. 这并没有遍历正确的次数。 What you want to be doing in my opinion is looping from 2 to the number of rows, like this: 我认为您想要做的是从2循环到行数,如下所示:

For x = 2 to LR 对于x = 2到LR
Range("F2:F" & X).FormulaR1C1 = "=VLOOKUP(&row&,[gpic.xlsx]Sheet1!$A:$D,4,FALSE)" Range(“ F2:F”&X).FormulaR1C1 =“ = VLOOKUP(&row&,[gpic.xlsx] Sheet1!$ A:$ D,4,FALSE)”

Replace E2 for a variable: 将E2替换为变量:

Dim row as String 昏暗的行作为字符串
row = "E2" 行=“ E2”

then use a loop to iterate through all E2,E3,E4 etc. 然后使用循环遍历所有E2,E3,E4等。

For x=2 to 20 do 对于x = 2到20
row = "E" & x 行=“ E”&x
formula = "VLOOKUP("&row&",[gpic.xlsx]Sheet1!$A:$D,4,FALSE)" 公式=“ VLOOKUP(”&row&“,[gpic.xlsx] Sheet1!$ A:$ D,4,FALSE)”
... use your code here ... ...在这里使用您的代码...

My VB may be a little rusty :/ 我的VB可能有点生锈:/
Hope this helps 希望这可以帮助

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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