来自不同工作表的Vlookup动态范围参考

时间:2019-12-20 08:11:43

标签: excel vba vlookup

我要在一系列单元格中插入一个vlookup公式。但是,该公式中具有动态参考,因此我很难正确地构造它。

这是我的代码:

Sheets("Count").Activate

Dim myValue As Date
myValue = InputBox("Please enter the date you want to update")
Sheets("Count").Range("A1").Value = myValue

Dim ra As Range, raEnd As Range
Dim date1 As Date
date1 = Range("A1")

Set ra = Cells.Find(What:=date1 _
                    , LookIn:=xlFormulas _
                    , LookAt:=xlPart _
                    , SearchOrder:=xlByRows _
                    , SearchDirection:=xlNext _
                    , MatchCase:=False _
                    , SearchFormat:=False)

    If ra Is Nothing Then
    MsgBox ("Date not found, check the format.")

    Else

        Dim Lastrow As Long, rng As Range
        Lastrow = Cells(Rows.Count, "B").End(xlUp).Row
        Set rng = Range(ra.Offset(1, 0), Cells(Lastrow, ra.Column))

        Dim endrow As Long, i As Long, lcol As Integer, startcells As Range
        lcol = Sheets("Count").Range("B1").Value
        endrow = Sheets("Input").Cells(Rows.Count, lcol).End(xlUp).Row
        i = 6
        Set startcells = Sheets("Input").Cells(i, lcol)

        Sheets("Input").Activate

        Dim xrnge As Range, s
        Set xrnge = Range(startcells, Cells(endrow, lcol))
        s = xrnge.Address

        Sheets("Count").Activate
        rng.Formula = "=IFERROR(VLOOKUP($B8,'" & "input" & "'!s,1,0),"""")"

    End If

End Sub

我无法工作的部分是

rng.Formula = "=IFERROR(VLOOKUP($B8,'" & "input" & "'!s,1,0),"""")"

我想我快到了,因为在要插入公式的范围内,像这样:

=IFERROR(VLOOKUP($B20;Input!s;1;0);"") 

您能帮我弄清楚为什么显示s而不显示范围本身吗?

1 个答案:

答案 0 :(得分:2)

如果我正确理解,您希望s保留一个范围地址,并且希望input成为静态工作表引用。在这种情况下,您应该这样写公式:

rng.Formula = "=IFERROR(VLOOKUP($B8,input!" & s & ",1,0),"""")"

s保留范围S3:S50的地址,单元格中的结果将是:

=IFERROR(VLOOKUP($B8,Input!$S$3:$S$50,1,0),"")

这将是预期的工作公式。