如果vlookup返回N / A,则Vba保留上一个单元格值或跳过

时间:2017-07-26 17:51:06

标签: excel vba excel-vba vlookup

我有大量国家数据及其生活费用指数。它们需要通过从网站复制表来每季度更新一次。

我创建了一个宏来查看更新后的索引并替换旧索引,但更新后的索引中不再存在某些条目,或者未包含这些条目。它使索引单元格保留#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单元格值它不是一种选择,但可能有不同的方式。

这是我运行后的样子。

Index Update

1 个答案:

答案 0 :(得分:2)

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

试试