简体   繁体   English

Excel VBA,将变量与VLOOKUp一起使用

[英]Excel VBA, using variables with VLOOKUp

I am trying to add a VLOOKUP to a column to enter data from one sheet to another. 我试图将VLOOKUP添加到列中,以将数据从一张纸输入到另一张纸。 The size of the table array on the look up sheet will vary so I want add a variable to formula. 查找表上表数组的大小会有所不同,因此我想向公式添加变量。

Here's what I have so far: 这是我到目前为止的内容:

Sheets("Page1_5").Select

Dim CountryRow As Long
Cells(5, 1).Select
Selection.End(xlDown).Select
CountryRow = ActiveCell.Row
Sheets("Results").Select
Range("B2").Select
 ActiveCell.FormulaR1C1 = "=VLOOKUP(RC[-1],Page1_5!$A$5:$F$" & CountryRow & ",6,FALSE)"

Any assistance would be gratefully received 任何帮助将不胜感激

You should stick to a method and go with it - in the beginning you are using Cells(5, 1).Select , later you are using Range("B2").Select and at last inside the VLookup you have both, RC[-1] and $A$5:$F$" & CountryRow . 您应该坚持并遵循一种方法-开始使用Cells(5, 1).Select ,之后使用Range("B2").Select并最后在VLookup中使用RC[-1]$A$5:$F$" & CountryRow

Also, there is no need to use Select , Selection and ActiveCell , but instead you could use fully qualified worksheets and ranges. 另外,不需要使用SelectSelectionActiveCell ,而是可以使用完全限定的工作表和范围。

Try the code below: 请尝试以下代码:

Option Explicit

Sub TestVlookup()

Dim CountryRow As Long

With Sheets("Page1_5")
    CountryRow = .Range("A5").End(xlDown).Row
End With

With Sheets("Results")
    Range("B2").Formula = "=VLOOKUP(A2,Page1_5!$A$5:$F$" & CountryRow & ",6,FALSE)"
End With

End Sub

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

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