首页 > 解决方案 > Excel VBA 条件 VLookup

问题描述

我正在使用 VLookup 函数Tabelle5.Range("A:A")根据Tabelle3.Cells(7 + i, 1). 如果在中找到标识号,Tabelle5.Range("A:A")则应将此行中的各个单元格复制到 (row) 中的右侧单元格中Tabelle3.Cells(7 + i, 1)。这适用于以下代码。

Sub VLookup

Dim lastrow As Long
Dim NFR As Long


lastrow = Tabelle5.Range("A" & Rows.Count).End(xlUp).Row
NFR = Tabelle3.Range("B" & Rows.Count).End(xlUp).Offset(-1).Row
Set myrange = Tabelle5.UsedRange


For i = 2 To lastrow


On Error Resume Next

    If Tabelle3.Cells(7 + i, 1) <> "" And Not IsError(Application.Match(Tabelle3.Cells(7 + i, 1), Tabelle5.Range("A:A"), False)) Then


        Tabelle3.Cells(7 + i, 2) = Application.WorksheetFunction.VLookup(Tabelle3.Cells(7 + i, 1), myrange, 2, False)


        Tabelle3.Cells(7 + i, 3) = Application.WorksheetFunction.VLookup(Tabelle3.Cells(7 + i, 1), myrange, 3, False)


        Tabelle3.Cells(7 + i, 4) = Application.WorksheetFunction.VLookup(Tabelle3.Cells(7 + i, 1), myrange, 4, False)

    End If

Next i

End Sub

我在这里面临的挑战是,可能存在Tabelle3已经包含数据的单元格。此数据将被来自 的“新”数据覆盖Tabelle5。但是,“新”数据可能Tabelle5是一个空单元格。这意味着我会丢失数据,因为填充的单元格将被空单元格覆盖。

编辑 是否有人知道如何应用 Vlookup,只有在(这就是我使用 Vlookup 的)中Tabelle3.Cells(7 + i, 1)也找到了来自的标识号,并且在第二步中只从.Tabelle5.Range("A:A")myrange Column 2,3, and 4

示例 中的标识号可在Tabelle3.Cells(12, 1)中找到Tabelle5.Cells(29,1)Row 29 in Tabelle5包含以下值:

在下一步中,我希望我的代码仅将 B29 和 D29 中的“新数据”复制到定义的单元格中, Tabelle3但跳过 C29,因为它是一个空单元格,这可能会覆盖Tabelle3.

标签: vbaexcelvlookup

解决方案


正如 Banana 建议的那样,您可以将 if 语句嵌套在另一个 if 语句下:

If Tabelle5.Cells(7 + i, 1) <> "" Then

    If Tabelle3.Cells(7 + i, 1) <> "" And Not IsError(Application.Match(Tabelle3.Cells(7 + i, 1), Tabelle5.Range("A:A"), False)) Then

        Tabelle3.Cells(7 + i, 2) = Application.WorksheetFunction.VLookup(Tabelle3.Cells(7 + i, 1), myrange, 2, False)

        Tabelle3.Cells(7 + i, 3) = Application.WorksheetFunction.VLookup(Tabelle3.Cells(7 + i, 1), myrange, 3, False)

        Tabelle3.Cells(7 + i, 4) = Application.WorksheetFunction.VLookup(Tabelle3.Cells(7 + i, 1), myrange, 4, False)

    End If

End If

更新:

在这种情况下,您可以使用 if 语句来应用每个 VLookup,如下所示:

If Application.WorksheetFunction.VLookup(Tabelle3.Cells(7 + i, 1), myrange, 2, False) <> "" Then Tabelle3.Cells(7 + i, 2) = Application.WorksheetFunction.VLookup(Tabelle3.Cells(7 + i, 1), myrange, 2, False)

或者

res1 = Application.WorksheetFunction.VLookup(Tabelle3.Cells(7 + i, 1), myrange, 2, False)
If res1 <> "" Then Tabelle3.Cells(7 + i, 2) = res1

整个逻辑肯定有更好的方法,但这至少应该有助于使您的代码正常工作。


推荐阅读