VBA保持以前的单元格值,或者如果vlookup返回N / A,则跳过

我有大量的国家数据和他们的生活成本指数。 他们需要每季度更新一次网站的表格。

我做了一个macros来查看更新的索引并replace旧的索引,但是一些条目不再存在于更新的索引中或者不包括在内。 它使用#N / A离开索引单元,但我宁愿保留旧的值。

'Varibles and format Dim last As Integer Dim Ending As Integer Dim examin As Variant Ending = Cells(Rows.Count, "A").End(xlUp).Row last = Range("G3").SpecialCells(xlCellTypeLastCell).Row Range("F3:F" & last).ClearContents Range("I3:M" & last).ClearContents 'Find & Replace country names with correct from Cells.Replace What:="United States", Replacement:="USA", LookAt:=xlPart, _ SearchOrder:=xlByRows, MatchCase:=False, SearchFormat:=False, _ ReplaceFormat:=False Cells.Replace What:="United Kingdom", Replacement:="England", LookAt:=xlPart, _ SearchOrder:=xlByRows, MatchCase:=False, SearchFormat:=False, _ ReplaceFormat:=False Cells.Replace What:="United Arab Emirates", Replacement:="United_Arab_Emirates", LookAt:=xlPart, _ SearchOrder:=xlByRows, MatchCase:=False, SearchFormat:=False, _ ReplaceFormat:=False Cells.Replace What:="Dominican Republic", Replacement:="Dominican_Republic", LookAt:=xlPart, _ SearchOrder:=xlByRows, MatchCase:=False, SearchFormat:=False, _ ReplaceFormat:=False Cells.Replace What:="South Africa", Replacement:="South_Africa", LookAt:=xlPart, _ SearchOrder:=xlByRows, MatchCase:=False, SearchFormat:=False, _ ReplaceFormat:=False Cells.Replace What:="Czech Republic", Replacement:="Czech_Republic", LookAt:=xlPart, _ SearchOrder:=xlByRows, MatchCase:=False, SearchFormat:=False, _ ReplaceFormat:=False Cells.Replace What:="Costa Rica", Replacement:="Costa_Rica", LookAt:=xlPart, _ SearchOrder:=xlByRows, MatchCase:=False, SearchFormat:=False, _ ReplaceFormat:=False 'Vlookup updated index For x = 2 To Ending Range("D" & x).Value = Application.VLookup(Range("A" & x), Range("G3:H" & last), 2, False) Next x End Sub 

我在这个问题上读到“如果VLOOKUP返回错误,如何保持以前的excel单元格值”,这不是一个选项,但可能有不同的方法。

这是它运行后的样子。

索引更新

 For x = 2 To Ending If isnumeric(Application.VLookup(Range("A" & x), Range("G3:H" & last), 2, False)) then Range("D" & x).Value = Application.VLookup(Range("A" & x), Range("G3:H" & last), 2, False) End if Next x End Sub 

试试看