VBA:如何在单元格中插入VLookup公式(而不是值)?

时间:2019-05-10 13:51:48

标签: excel vba

我正在设置Excel工作簿中键的“数据库”(混合业务线,业务部门和其他一些信息)。 我需要使用这些键进行VLookup,并在另一个Excel工作簿中搜索这些键。我想通过VBA做到这一点。

Sub CreateVLookUp()
    Dim rw As Long, x As Range
    Dim extwbk As Workbook, twb As Workbook
    Dim KeyRange As Range
    Dim KeyCell As Range
    Dim lastrow As Long

    lastrow = Worksheets("Parameters").Range("I" & Rows.Count).End(xlUp).Row
    Set KeyRange = Worksheets("Parameters").Range("I8:I" & lastrow)

    Set twb = ThisWorkbook
    Set extwbk = Workbooks.Open("C:\Users\vih8452\Documents\ExcelFile.xlsx")
    Set x = extwbk.Worksheets("Database Structure").Range("$A:$T")



    With twb.Sheets("Parameters")

        For rw = 15 To .Cells(Rows.Count, 10).End(xlUp).Row
            .Cells(rw, 14) = Application.VLookup(.Cells(rw, 9).Value2, x, 15, False)
            .Cells(rw, 15) = Application.VLookup(.Cells(rw, 9).Value2, x, 11, False)
            .Cells(rw, 16) = Application.VLookup(.Cells(rw, 9).Value2, x, 12, False)
        Next rw

    End With

    extwbk.Close savechanges:=False
End Sub

我的任务已经差不多成功了,但是主要的问题是,当我运行VBA宏时,它只是粘贴了结果。 我想要的是在单元格中看到结果,还要在公式栏中看到公式(以便可以检查结果是对还是错)。

2 个答案:

答案 0 :(得分:2)

设置公式时不需要循环:

Sub CreateVLookUp()
    Dim x As Range
    Dim extwbk As Workbook
    Dim lastrow As Long

    Set extwbk = Workbooks.Open("C:\Users\vih8452\Documents\ExcelFile.xlsx")
    Set x = extwbk.Worksheets("Database Structure").Range("$A:$T")

    With ThisWorkbook.Sheets("Parameters")

        lastrow = .Range("I" & Rows.Count).End(xlUp).Row
        .Range(.Cells(15, 14), .Cells(lastrow, 14)).Formula = "=VLOOKUP(I15," & x.Address(1, 1, xlA1, 1) & ",15,FALSE)"
        .Range(.Cells(15, 15), .Cells(lastrow, 15)).Formula = "=VLOOKUP(I15," & x.Address(1, 1, xlA1, 1) & ",11,FALSE)"
        .Range(.Cells(15, 16), .Cells(lastrow, 16)).Formula = "=VLOOKUP(I15," & x.Address(1, 1, xlA1, 1) & ",12,FALSE)"

    End With
    extwbk.Close savechanges:=False
End Sub

答案 1 :(得分:1)

您必须这样写:

 .Cells(rw, 14).FormulaR1C1 = "=VLOOKUP(" & .Cells(rw, 9).Value & ", C1:C20, 15, FALSE)"

 .Cells(rw, 14).FormulaR1C1 = "=VLOOKUP(RC[-5], C1:C20, 15, FALSE)"

要引用另一张纸,只需放置:

 .Cells(rw, 14).FormulaR1C1 = "=VLOOKUP('Sheet Name'!RC[-5], 'Sheet Name'!C1:C20, 15, FALSE)"