在VBA中如何将范围变量放入VLOOKUP中?

在VBA中如何将范围变量放入VLOOKUP中?,vba,excel,Vba,Excel,我使用以下宏在两列之间执行VLOOKUP函数: Sub ExcelJoin() On Error Resume Next Dim Dept_Row1 As Long Dim Dept_Clm1 As Long Dim LastRowA As Long Dim LastColO As Long Set currentsheet = ActiveWorkbook.Sheets(1) ctr = 0 LastRowA = currentsheet.Range("A" & Rows.Cou

我使用以下宏在两列之间执行VLOOKUP函数:

Sub ExcelJoin()
On Error Resume Next
Dim Dept_Row1 As Long
Dim Dept_Clm1 As Long
Dim LastRowA As Long
Dim LastColO As Long

Set currentsheet = ActiveWorkbook.Sheets(1)
ctr = 0


LastRowA = currentsheet.Range("A" & Rows.Count).End(xlUp).Row
LastRowO = currentsheet.Range("O" & Rows.Count).End(xlUp).Row
Table1 = currentsheet.Range("A2:A" & LastRowA)
Table2 = currentsheet.Range("O2:O" & LastRowO)


Dept_Row1 = currentsheet.Range("B2").Row
Dept_Clm1 = currentsheet.Range("B2").Column
For Each cl In Table1
  currentsheet.Cells(Dept_Row1, Dept_Clm1).FormulaR1C1 = "=VLOOKUP(RC[-1], R2C15:R14C15, 1, False)"
  Dept_Row1 = Dept_Row1 + 1
  ctr = ctr + 1
Next cl

End Sub
但由于R2C15:R14C15范围内的行数未知,我应该使用LastRowO将R14作为变量。但是我在合成酶方面有一些问题,因为我不知道如何以正确的方式将这个变量放入VLOOKUP中。

这个应该可以工作:

currentsheet.Cells(Dept_Row1, Dept_Clm1).FormulaR1C1 = "=VLOOKUP(RC[-1], R2C15:R" & LastRowO & "C15, 1, False)"
顺便说一句,对于表1中的每个cl,不需要使用循环
。您可以在一行代码中将公式应用于整个范围

更改:

For Each cl In Table1
  currentsheet.Cells(Dept_Row1, Dept_Clm1).FormulaR1C1 = "=VLOOKUP(RC[-1], R2C15:R14C15, 1, False)"
  Dept_Row1 = Dept_Row1 + 1
  ctr = ctr + 1
Next cl


非常感谢。它与“&LastRowO&”完美配合!关于循环,我只是不确定,因为我认为“B2:A”和LastRowA可能是错误的,实际上它们是一样的。作为代码
Table1=currentsheet.Range(“A2:A”和LastRowA)
的后续操作,然后循环遍历Range
Range(“A2:A”和LastRowA)中的每个单元格,并将公式添加到col
B
中的相应值中。在这种情况下,使用
currentsheet.Range(“B2:A”和LastRowA).FormulaR1C1
:)更简单。啊,我明白了逻辑,你是对的。但是如果我做范围代换,它会返回一个空的B列,而不是Vlookup,这就是为什么我认为这可能是错误的。
currentsheet.Range("B2:A" & LastRowA).FormulaR1C1 = "=VLOOKUP(RC[-1], R2C15:R" & LastRowO & "C15, 1, False)"