【问题标题】:How do I write the lookup_value in vlookup VBA as a range如何将 vlookup VBA 中的 lookup_value 写为范围
【发布时间】:2017-02-07 13:19:31
【问题描述】:

我是 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

【问题讨论】:

    标签: vba excel vlookup


    【解决方案1】:

    如果我能够从您的代码中理解您想要实现的目标,请尝试以下代码:

    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
    

    【讨论】:

    • @ifeelcrazy123 你测试过我答案中的代码吗?
    • 非常感谢。那行得通! (这么晚才回复很抱歉)。仅供参考,我需要右侧 9 列的值,因为前面的 8 列填充了其他数据,我需要比较这些数据并将其提交到金融系统中。谢谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-02-28
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多