簡體   English   中英

如何在vlookup VBA中將lookup_value寫入范圍

[英]How do I write the lookup_value in vlookup VBA as a range

我是VBA的新手-我試圖在Excel中編寫Vlookup函數,以將lookup_value引用為一系列值。 我將值存儲在一個名為lookup_range的范圍內,但是當我將vlookup值輸出到單元格時,我得到的結果是N / A。

我已經在整個互聯網上進行了搜索,但是我的問題沒有任何解決方案。

Sub Vlookup_values()

    Dim Vlkp_cell, n As Double
    Dim Search_range, row_end, col_end As Double

    Sheets("Movement").Activate
    Range("A1").End(xlDown).Select
    Vlkp_cell = ActiveCell.Row

    ReDim Lookup_range(Vlkp_cell) As String
    n = 0
    Range("A1").Select
    For n = 1 To Vlkp_cell
        ActiveCell.Offset(1, 0).Select
        Lookup_range(n) = ActiveCell.Value
        ActiveCell.Offset(0, 9).Value = Lookup_range(n)
    Next n

    Sheets("Mapping").Activate
    Range("A1").End(xlDown).Select
    row_end = ActiveCell.Row

    Range("A1").End(xlToRight).Select
    col_end = ActiveCell.Column

    Range(Cells(1, 1), Cells(row_end, col_end)).Name = "Search_range"
    Range("Search_Range").Select

    Sheets("Movement").Activate
    Range("A1").Select
    ActiveCell.Offset(0, 1).Select
    n = 0
    For n = 1 To Vlkp_cell

        ActiveCell.Offset(1, 0).Select
        ActiveCell.Value = Application.VLookup(Lookup_range(n), Search_range, 2, False)

    Next n


End Sub

如果我能夠通過代碼理解您要實現的目標,請嘗試以下代碼:

Option Explicit

Sub Vlookup_values()

    Dim Vlkp_cell As Long, n As Long
    Dim Search_range As Range, row_end As Long, col_end As Long

    With Sheets("Mapping")
        row_end = .Range("A1").End(xlDown).Row
        col_end = .Range("A1").End(xlToRight).Column

        Set Search_range = .Range(.Cells(1, 1), .Cells(row_end, col_end)) ' <-- set the Range for the VLookup
    End With

    With Sheets("Movement")
        Vlkp_cell = .Range("A1").End(xlDown).Row

        For n = 1 To Vlkp_cell
            .Range("A" & n).Offset(0, 9).Value = .Range("A" & n).Value ' <-- not sure why you need the values copied 9 column to the right ?
            .Range("B" & n).Value = Application.VLookup(.Range("A" & n).Value, Search_range, 2, False)
        Next n
    End With

End Sub

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM