如何使用Application.VLookup防止数据丢失?

时间:2019-03-13 17:48:59

标签: excel vba

以下宏在两个工作簿之间利用VLookup函数。两个工作簿都包含表。目的是让 book1 更新 book2

中的值

每当 book2 中不存在查找值时,就会发生数据丢失(在 book1 中具有值的单元格被删除)。这就引出我的问题:如何防止这种删除的发生?

Sub Update()
Dim lookFor As Range
Dim srchRange As Range

Dim book1 As Workbook
Dim book2 As Workbook

Dim book2Name As String
book2Name = "table2.xlsm"

Dim book2NamePath As String
book2NamePath = ThisWorkbook.Path & "\" & book2Name

Set book1 = ThisWorkbook

If IsOpen(book2Name) = False Then Workbooks.Open (book2NamePath)
Set book2 = Workbooks(book2Name)

Set lookFor = book1.Sheets(1).Range("a23:a100")
Set srchRange = book2.Sheets(1).Range("b:f")

lookFor.Offset(0, 7).Value = Application.VLookup(lookFor, srchRange, 2, False)

End Sub

1 个答案:

答案 0 :(得分:0)

测试返回值,仅在有返回值时更新。

Dim val as Variant

Set lookFor = book1.Sheets(1).Range("a23:a100")
Set srchRange = book2.Sheets(1).Range("b:f")

val = Application.VLookup(lookFor.Cells(1), srchRange, 2, False)

If Not IsError(val) Then
    lookFor.Offset(0, 7).Value = val
End If

您可以使用Application.VLookup或Application.Match测试返回的变体。它必须返回一个变体,并且不能与WorksheetFunction.VLookup或WorksheetFunction.Match一起使用。