vba - 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
包含以下值:
- A29识别号
- B29 新数据
- C29 空
- D29 新数据
在下一步中,我希望我的代码仅将 B29 和 D29 中的“新数据”复制到定义的单元格中, Tabelle3
但跳过 C29,因为它是一个空单元格,这可能会覆盖Tabelle3
.
解决方案
正如 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
整个逻辑肯定有更好的方法,但这至少应该有助于使您的代码正常工作。
推荐阅读
- powershell - 无法解析 Get-WinEvent 消息正文?
- react-native - 用 Axios 反应原生图片上传错误:网络错误
- python-3.x - 如何根据其他df中的条件和值为pandas df中的新列分配值?
- ios - 在 Xcode 12 中使用 SPM 时的 iOS 部署目标问题
- python - 根据其他字典的值对字典的值进行排序
- c - getline() 从文本文件读取时读取垃圾值
- python-3.x - 如何从 django 中可用的大量 csv 文件中选择一个 csv 文件
- c++ - C++ 更新 unordered_map 中的值,其中键值对的数据类型为 int-unordered_set
- javascript - React中字符串的正则表达式
- excel - VBA宏根据日期将单元格值从工作表1复制/粘贴到2