【发布时间】:2021-05-08 22:38:33
【问题描述】:
我正在尝试自动填充 Vlookup 公式,在另一个工作表中查找值。工作簿中有两个工作表,供应商和产品。产品代码从供应商工作表的产品工作表中查找。
这是代码:
Dim lastrow As Long
Sheets("Suppliers").Select
lastrow = ActiveSheet.UsedRange.Rows.Count
Dim SuppliersRnge As Range
Set SuppliersRnge = Range(Cells(2, 2), Cells(lastrow, 3))
' This next try was by declaring the first and last rows and columns in Suppliers sheet as variables and passing values to them (passing values not shown here)
' Set SuppliersRnge = .Range(.Cells(SupplierFirstRow, SupplierFirstColumn), .Cells(SupplierLastRow, SupplierLastColumn))
' This next try was by declaring the range as a static set of cells rather than using lastrow
' Set SuppliersRnge = Range("B2:C23")
' This next try was to pick cell references from currently active worksheet
' Set SuppliersRnge = .Range(.Cells(2, 2), .Cells(lastrow, 3))
' This next try was by fully qualifying the name of the worksheet from which the cell reference is drawn
' Set SuppliersRnge = Worksheets(Suppliers).Range(Cells(2, 2), Cells(lastrow, 3))
' Now switching to product sheet
Sheets("Products").Select
' Selecting cell in which vlookup will be added
Range("A4").Select
ActiveCell.FormulaR1C1 = "=VLOOKUP(RC[1],SuppliersRnge,2,FALSE)"
我将 SuppliersRnge 声明为一个范围,并使用 Set 将需要查找的单元格范围传递给它。
我尝试了五种不同的方法(你会发现上面注释掉的四种方法),结果相同,即字符串 SuppliersRnge 在 vlookup 中被使用,导致 >#NAME? Vlookup 的结果应该是的值。
当我在 立即 窗口中运行 ?SuppliersRnge 时,我得到 Type Mismatch (Run-time Error 13)。
如果我对 SuppliersRnge 变量运行 Watch,它会以“Nothing”值开始,然后变为空白。
知道我哪里可能出错了吗?谢谢!
【问题讨论】:
-
您似乎混淆了range 和named range。这是如何在公式中使用您在代码中定义的范围。 ActiveCell.FormulaR1C1 = "=VLOOKUP(RC[1]," & SuppliersRnge.Parent.Name & "!" & SuppliersRnge.Address(False, False) & ",2,FALSE)"跨度>