简体   繁体   English

使用宏的Excel中的VLookup函数范围

[英]VLookup function range in Excel using macro

I am trying to make a macro to do the vlookup in excel. 我正在尝试制作一个宏以在Excel中执行vlookup。 I have succeed to create and the code is working fine! 我已经创建成功,代码运行正常! The code as below: 代码如下:

ActiveCell.FormulaR1C1 = _ "=VLOOKUP(RC[-1],LW0640!R2C8:R12163C9,2,TRUE)" Selection.AutoFill Destination:=Range("D6:D6098")

However, I found that the range is fix range. 但是,我发现范围是固定范围。 which is from D6:D6098 on the result and R2C8:R12163C9 from the source. 其结果来自D6:D6098,源来自R2C8:R12163C9。

And it will not work if the data range changes. 如果数据范围更改,它将不起作用。 I want to know how to make the range for the vlookup function from the beginning until the last row in the range. 我想知道如何从范围的开头到最后一行为vlookup函数设置范围。 Please help! 请帮忙!

You can use the "A1" type of notation. 您可以使用“ A1”类型的表示法。 In your case, you want column 8 and 9, which are respectively H and I, so you can write the following: 对于您的情况,您需要第8列和第9列,分别为H和I,因此您可以编写以下内容:

ActiveCell.FormulaR1C1 = _
"=VLOOKUP(RC[-1],LW0640!H:I" & MyCols & ",2,TRUE)"
Selection.AutoFill Destination:=Range("D6:D6098")

You can use this code. 您可以使用此代码。

Sheets("LW0640").Select
Range("D6:D6098").Select
    ActiveWorkbook.Names.Add Name:="tablex", RefersToR1C1:= _
        "=LW0640!R6C4:R6098C4"


'Range("F28").Select
ActiveCell.FormulaR1C1 = "=VLOOKUP(RC[-1],tablex,2,TRUE)"

Try 尝试

Sub Demo()
    Dim ws As Worksheet
    Dim LastRow As Long

    Set ws = ThisWorkbook.Sheets("Sheet1")  'change Sheet1 to your data sheet
    With ws
        LastRow = .Range("H" & .Rows.Count).End(xlUp).Row
        .Range("D6:D" & LastRow).Formula = "=VLOOKUP(C6,LW0640!$H$2:$I$" & LastRow & ",2,TRUE)"
    End With
End Sub

You should avoid using SELECT and ACTIVE . 您应该避免使用SELECTACTIVE See this for details. 请参阅了解详情。

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

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