如何用VBA实现Entry工作表E14及下方单元格的VLOOKUP自动填充?
用VBA实现指定VLOOKUP需求的方案
完全可以用VBA实现你的需求,下面提供两种实用方案,适配不同场景:
方案1:批量写入VLOOKUP公式(和手动输入公式效果一致)
这种方法直接给目标单元格批量写入VLOOKUP公式,后续源数据变化时结果会自动更新,操作简单:
Sub ApplyVLOOKUPFormula() Dim wsEntry As Worksheet Dim wsConversion As Worksheet Dim lastRow As Long ' 绑定工作表对象 Set wsEntry = ThisWorkbook.Worksheets("Entry") Set wsConversion = ThisWorkbook.Worksheets("Conversion") ' 找到Entry表E列最后有数据的行(从E14开始向下查找) lastRow = wsEntry.Cells(wsEntry.Rows.Count, "E").End(xlUp).Row ' 如果E14及以下无数据,直接退出程序 If lastRow < 14 Then Exit Sub ' 批量写入VLOOKUP公式 ' 注:第三个参数3表示返回Conversion表C列的对应值,若需返回B列可改为2 wsEntry.Range("E14:E" & lastRow).Formula = _ "=VLOOKUP(E14,Conversion!$A$2:$C$300,3,FALSE)" End Sub
方案2:用字典实现匹配(直接写入结果值,更高效)
如果数据量较大,用字典匹配后直接写入结果值,运行速度比公式更快,缺点是后续源数据变化不会自动更新,需要重新运行代码:
Sub VLOOKUPWithDictionary() Dim wsEntry As Worksheet Dim wsConversion As Worksheet Dim conversionData As Variant Dim lookupDict As Object Dim i As Long Dim lastRowEntry As Long Dim lastRowConversion As Long Set wsEntry = ThisWorkbook.Worksheets("Entry") Set wsConversion = ThisWorkbook.Worksheets("Conversion") Set lookupDict = CreateObject("Scripting.Dictionary") ' 获取Conversion表A到C列的有效数据 lastRowConversion = wsConversion.Cells(wsConversion.Rows.Count, "A").End(xlUp).Row conversionData = wsConversion.Range("A2:C" & lastRowConversion).Value ' 将Conversion表A列作为匹配键,C列作为结果存入字典 For i = LBound(conversionData) To UBound(conversionData) If Not lookupDict.Exists(conversionData(i, 1)) Then lookupDict(conversionData(i, 1)) = conversionData(i, 3) End If Next i ' 处理Entry表E列的目标数据 lastRowEntry = wsEntry.Cells(wsEntry.Rows.Count, "E").End(xlUp).Row If lastRowEntry < 14 Then Exit Sub ' 遍历匹配并写入结果 For i = 14 To lastRowEntry If lookupDict.Exists(wsEntry.Cells(i, "E").Value) Then wsEntry.Cells(i, "E").Value = lookupDict(wsEntry.Cells(i, "E").Value) Else ' 未匹配到的情况可自定义,这里设为空值,也可改为"=NA()" wsEntry.Cells(i, "E").Value = "" End If Next i End Sub
注意事项
- 你提供的原VLOOKUP公式缺少第三个参数(返回列的索引),代码中默认使用3(对应Conversion表的C列),如果需要返回B列数据,将代码中的
3修改为2即可。 - 确保Entry表E列的账户数据和Conversion表A列的关键字格式一致(比如都是文本或数字),避免匹配失败。
内容的提问来源于stack exchange,提问作者Fred Blair
相关产品推荐
相关产品推荐

