尝试将vlookup添加到Excel

时间:2018-01-25 16:45:35

标签: excel vba excel-vba vlookup

我正在尝试创建一个公式,用于检查单元格中是否有值,然后在A列中输入vlookup。作为标准公式,它看起来像

=VLOOKUP(B2,'Date Shown'!A:E,7,FALSE)

我希望查找值能够根据最初检查的单元格进行更改。我有以下公式,可以检查并添加一个值到相邻的单元格,我试图修改为vlookup,但没有正确创建vlookup的知识。感谢任何帮助,谢谢!

Option Explicit

Sub Macro1()

Dim r As Range
Dim LastRow As Long

With Sheets("Date Hidden")
    LastRow = .Cells(.Rows.Count, "B").End(xlUp).Row

    For Each r In .Range("B2:B" & LastRow)
        If r.Value <> "" Then
            r.Offset(0, -1).result = Application.WorksheetFunction.VLookup(Sheets("Date Hidden").Range("A2"), Sheets("Date Shown")A:G, 7, False)
        End If
    Next r
End With

End Subs

显示日期表:

A栏//列G

Jane / / 10/1/17

日期隐藏表

A栏//栏B (空)//简

1 个答案:

答案 0 :(得分:0)

更改了一些代码:

    Option Explicit

    Sub Macro1()

    Dim i As Long
    Dim date_hidden_range As Range
    Dim last_row As Long

    With Sheets("Date Hidden")
        last_row = .Cells(.Rows.Count, "B").End(xlUp).Row

        Set date_hidden_range = .Range("B2:B" & last_row)

        For i = 1 To date_hidden_range.Cells.Count
            If date_hidden_range(i).Value <> "" Then
                MsgBox date_hidden_range(i).Value
                date_hidden_range(i).Value = Application.WorksheetFunction.VLookup(Sheets("Date Hidden").Range("A" & i), Sheets("Date Shown").Range("A:G"), 7, False)
            End If
        Next i

    End With

    End Sub

选项2

    Option Explicit

    Sub Macro1()

    Dim i As Long
    Dim cell_range As Range
    Dim date_hidden_range As Range
    Dim last_row As Long

    With Sheets("Date Hidden")
        last_row = .Cells(.Rows.Count, "B").End(xlUp).Row

        Set date_hidden_range = .Range("B2:B" & last_row)

        For Each cell_range In date_hidden_range
        i = 2
            If cell_range(i).Value <> "" Then
                MsgBox cell_range(i).Value
                cell_range(i).Value = Application.WorksheetFunction.VLookup(Sheets("Date Hidden").Range("A" & i), Sheets("Date Shown").Range("A:G"), 7, False)
            End If
        i = i + 1
        Next cell_range

    End With

    End Sub

检查这项工作的方式,希望这对您有所帮助。