You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何让VBA中Vlookup无匹配时不返回#NA且保留原有值

解决VLookup无匹配时不覆盖单元格原有值的问题

修改后的代码

Dim ws As Worksheet: Set ws = wb.Sheets("Existing")
Dim srg As Range: Set srg = ws.Columns("A:AJ")
Dim lastRow As Long
lastRow = ws.Cells(ws.Rows.Count, "A").End(xlUp).Row

Dim i As Long
For i = 2 To lastRow
    ' 处理P列:仅当VLookup找到匹配时更新单元格
    Dim vLookupResultP As Variant
    vLookupResultP = Application.VLookup(ws.Cells(i, "A").Value, srg, 35, 0)
    If Not IsError(vLookupResultP) Then
        ws.Cells(i, "P").Value = vLookupResultP
    End If
    
    ' 处理Q列:仅当VLookup找到匹配时更新单元格
    Dim vLookupResultQ As Variant
    vLookupResultQ = Application.VLookup(ws.Cells(i, "A").Value, srg, 36, 0)
    If Not IsError(vLookupResultQ) Then
        ws.Cells(i, "Q").Value = vLookupResultQ
    End If
Next i

关键修改说明

  • 保留原有值逻辑:用IsError函数判断VLookup返回结果,仅当结果不是错误值(即找到匹配项)时,才更新目标单元格;无匹配返回#NA错误时,直接跳过赋值操作,保留单元格原有内容。
  • 优化运行效率:将原有的两个独立循环合并为一个,减少行遍历次数,提升代码执行速度。
  • 简化变量定义:原代码中sws和dws指向同一个工作表,合并为ws变量,让代码结构更简洁。

内容的提问来源于stack exchange,提问作者little turtle

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.27 07:02:36