VBA VLookup问题

时间:2016-04-20 05:11:53

标签: excel vba vlookup

我在使用下面的VLookup时遇到问题,因为我使用完整列范围作为查找值。

Private Sub Worksheet_Activate()

Dim WsFk_Row As Long
Dim WsFk_Clm As Long

Table1 = Sheets("Requirements Update Format").Range("A:A")
Table2 = Sheets("Workstreams Link").Range("A:B")
Set WsFk_Row = Sheets("Requirements Insert Format").Range("I1").Row
Set WsFk_Clm = Sheets("Requirements Insert Format").Range("I1").Column


For Each cl In Table1
    Sheets("Requirements Insert Format").Cells(WsFk_Row, WsFk_Clm) = Application.WorksheetFunction.VLookup(cl, Table2, 2, False)
    WsFk_Row = WsFk_Row + 1
Next cl

End Sub

此代码适当地填充所有行,但是一旦完成,我会收到以下错误"无法获取WorksheetFunction类的#eleookup属性"。这让我相信以下几行是我的问题开始的地方

Table1 = Sheets("Requirements Update Format").Range("A:A")

我尝试通过修改如下所示的行来解决这个问题,但这阻止了该进程的运行。

Table1 = Sheets("Requirements Update Format").Range(Range("A1"), Range("A1").End(xlDown).Select)

对于如何解决这个问题的任何建议都将不胜感激。

2 个答案:

答案 0 :(得分:2)

编辑用“.Find”方法替换“VlookUp”并处理可能的不匹配

Dim WsFk_Row As Long, WsFk_Clm As Long
Dim found as Range
With Sheets("Requirements Update Format")

    Set Table1 = .Range("A1:A" & .Cells(.Rows.Count,1).End (xlUp).Row)

End With

Set Table2 = Sheets("Workstreams Link").Range("A:B")

WsFk_Row = Sheets("Requirements Insert Format").Range("I1").Row

WsFk_Clm = Sheets("Requirements Insert Format").Range("I1").Column


For Each cl In Table1
   Set found = Table2. Columns(1).Find (What:=cl.Value, LookAt:=xlWhole,  LookIn:=xlValues, MatchCase=True)
   If Not found is Nothing then Sht3.Cells(WsFk_Row, WsFk_Clm) =  found.Offset (,1)
   WsFk_Row = WsFk_Row + 1
Next cl

End Sub

答案 1 :(得分:1)

我认为你走在了正确的轨道上。请尝试以下方法......

Private Sub Worksheet_Activate()

Dim WsFk_Row As Long, WsFk_Clm As Long
Dim Sht1 As Worksheet, Sht2 As Worksheet, Sht3 As Worksheet
Dim Table1 As Range, Table2 As Range
Dim cl As Range
Dim lastRow As Long

Set Sht1 = Worksheets("Requirements Update Format")
Set Sht2 = Worksheets("Workstreams Link")
Set Sht3 = Worksheets("Requirements Insert Format")

lastRow = Sht1.Range("A" & Sht1.Rows.Count).End(xlUp).Row
Set Table1 = Sheets("Requirements Update Format").Range("A1:A" & lastRow)

lastRow = Sht2.Range("A" & Sht2.Rows.Count).End(xlUp).Row
Set Table2 = Sheets("Workstreams Link").Range("A1:B" & lastRow)

WsFk_Row = Sht3.Range("I1").Row
WsFk_Clm = Sht3.Range("I1").Column

For Each cl In Table1
    Sht3.Cells(WsFk_Row, WsFk_Clm) = Application.WorksheetFunction.VLookup(cl, Table2, 2, False)
    WsFk_Row = WsFk_Row + 1
Next cl

Set Sht1 = Nothing
Set Sht2 = Nothing
Set Sht3 = Nothing
Set Table1 = Nothing
Set Table2 = Nothing

End Sub

这样做:

  • 使用更多对象,希望提高可读性
  • 更正了Set
  • 周围的一些语法
  • 计算表格的实际大小。这可以防止cl循环射击超出可用范围的末尾。
  • 最后清理对象 - 只是好习惯