如何在VBA中存储和写入Vlookup结果

时间:2015-11-20 10:12:51

标签: excel-vba vlookup vba excel

我在VBA中对Vlookup感到生气! 场景: 我有两张纸:MySheet和OtherSheet。 查找值:MySheet中的列ID_Consegna 搜索范围:OtherSheet中的matrice 索引:6和7(所以我需要获得两个值)

然后我必须写下从MySheet的G和H列的公式中获得的这些值。

我到目前为止所做的代码是:

Sub cerca_vert()

'definisco il foglio attivo
Dim mySheet As Worksheet
Set mySheet = Worksheets("data")
Set otherSheet = Worksheets("data (2)")
mySheet.Activate

'definisco la colonna ID_Consegna
Dim cella_indirizzo As Variant

Dim lLastRow As Long
lLastRow = mySheet.Cells(mySheet.Rows.Count, 6).End(xlUp).Row
Dim ID_Consegna As Variant
ID_Consegna = mySheet.Range("F2:F" & lLastRow)


'definisco la matrice di ricerca nel secondo foglio "data (2)"
Dim val1_cap As Integer
Dim val2_citta As Variant

Dim lLastRow_matrice As Long
lLastRow_matrice = otherSheet.Cells(otherSheet.Rows.Count, 4).End(xlUp).Row
Dim matrice As Variant
matrice = otherSheet.Range("D2:I" & lLastRow)

For Each cella_indirizzo In ID_Consegna
    On Error Resume Next
    val1 = Application.WorksheetFunction.VLookup(CStr(cella_indirizzo), matrice, 6, False)
    val2 = Application.WorksheetFunction.VLookup(CStr(cella_indirizzo), matrice, 7, False).Value
Next cella_indirizzo
End Sub

我的问题是:

  1. 为什么val1和val2保持为空?
  2. 我怎么能"填充"它们?
  3. 我怎么能"填充"它们?

    非常感谢能帮助我的人!

1 个答案:

答案 0 :(得分:0)

如果您想要从F列和G列中获得结果,那么

Sub cerca_vert()

'definisco il foglio attivo
    Dim mySheet As Worksheet, OtherSheet As Worksheet
    Dim cella_indirizzo As Range    ' in loop
    Dim lLastRow As Long
    Dim ID_Consegna As Range
    Dim val1, val2
    Dim lLastRow_matrice As Long
    Dim matrice As Range

    Set mySheet = Worksheets("data")
    Set OtherSheet = Worksheets("data (2)")

    'definisco la colonna ID_Consegna

    lLastRow = mySheet.Cells(mySheet.Rows.Count, 6).End(xlUp).Row
    Set ID_Consegna = mySheet.Range("F2:F" & lLastRow)
    lLastRow_matrice = OtherSheet.Cells(OtherSheet.Rows.Count, 4).End(xlUp).Row
    Set matrice = OtherSheet.Range("D2:I" & lLastRow)

    'definisco la matrice di ricerca nel secondo foglio "data (2)"

    For Each cella_indirizzo In ID_Consegna.Cells
        On Error Resume Next
        val1 = Application.WorksheetFunction.VLookup(CStr(cella_indirizzo), matrice, 3, False)
        val2 = Application.WorksheetFunction.VLookup(CStr(cella_indirizzo), matrice, 4, False)
        cella_indirizzo.Offset(, 1) = val1
        cella_indirizzo.Offset(, 2) = val2
    Next cella_indirizzo

End Sub