使用VBA进行简单的vlookup遇到麻烦

时间:2019-03-22 19:57:29

标签: excel vba excel-formula

我有一个主电子表格,我正在执行该程序来分析另一个电子表格中的记录,并且行数一直达到140万。除vlookup之外,我已将大部分任务自动化。

以下是代码中的相关内容: 代码被卡在以下行:

"=ifna(vlookup(O" & i & "," & ISINL & "First Sheet'!$B:$C,2,false)," & Chr(34) & "N" & Chr(34) & ")" 

每当找到结果并且错误是应用程序定义的错误时。有人知道为什么吗?

Sub Whyamidoingthis()

Dim USISINLfp As String
Dim ISINL As String
Dim echeck As String
Dim wUSISIN As Workbook
Dim lastrow As Long
Dim Result As Worksheet
Dim i As Long
Set OutShVar = ThisWorkbook.Worksheets("in1")
ISINL = "CONSOLIDATED - Country_Of_Incorp_US_2019-03-01 (Consolidated).xlsx"

USISINLfp = "W:\Product Platforms\ISIN- CUSIP Country of Incorporation\March 2019\"

 Workbooks.Open (USISINLfp & ISINL)
Set wUSISIN = Workbooks(ISINL)

With Result
    lastrow = .Cells(.Rows.Count, "H").End(xlUp).Row
End With

 'US Security 1

   For i = 2 To lastrow
  With Result
  echeck = Trim(.Range("O" & i))
  If echeck = "" Then
      .Range("P" & i & ":Q" & i).Value = "N"
  Else
      .Range("P" & i).Value = "=ifna(vlookup(O" & i & "," & ISINL & "First Sheet'!$B:$C,2,false)," & Chr(34) & "N" & Chr(34) & ")"
      .Range("Q" & i).Value = "=ifna(vlookup(O" & i & "," & ISINL & "Second Sheet'!$B:$C,2,false)," & Chr(34) & "N" & Chr(34) & ")"
      'Debug.Print "=ifna(vlookup(O" & i & "," & ISINL & "Second Sheet'!$B:$C,2,0)," & Chr(34) & "N" & Chr(34) & ")"
  End If

  'US Security 2
  echeck = Trim(.Range("S" & i))
  If echeck = "" Then
      .Range("T" & i & ":U" & i).Value = "N"
  Else
  .Range("T" & i).Value = "=ifna(vlookup(S" & i & "," & ISINL & "First Sheet'!$A:$C,3,false)," & Chr(34) & "N" & Chr(34) & ")"
.Range("U" & i).Value = "=ifna(vlookup(S" & i & "," & ISINL & "Second Sheet'!$A:$C,3,false)," & Chr(34) & "N" & Chr(34) & ")"
  End If


End With
Next i
If Not wUSISIN Is Nothing Then wUSISIN.Close savechanges:=False
End Sub

1 个答案:

答案 0 :(得分:0)

尝试以下公式:

"=ifna(vlookup(O" & i & ",'[" & ISINL & "]First Sheet'!$B:$C,2,false)," & Chr(34) & "N" & Chr(34) & ")"

这会在工作簿名称周围放置方括号,并在工作簿-工作表组合周围放置单引号。有关从另一个工作簿中使用VLOOKUP的信息,请参见this tutorial