我在Excel中有下表。
result
列的计算公式为:
IF(ISERROR(VLOOKUP(A2,$B$2:$B$8,1,0)),"new","old")
ID1 | ID2 | Result
------------------
1 | 1 | Old
2 | 5 | New
3 | 6 | New
问题:将公式转换为VBA。我不知道如何将结果写入Result
列。
我有什么:
Sub Macro()
Dim result As Variant
Dim wb As Workbook
Dim ws As Worksheet
Dim table1 As Range
Dim table2 As Range
Set wb = ActiveWorkbook
Set ws = wb.Sheets(1)
Set table1 = ws.Range("A2:A8") ' ID1 column
Set table2 = ws.Range("B2:B8") ' ID2 column
For Each cell In table1
On Error GoTo ErrorHandler
result = Application.WorksheetFunction.VLookup(cell, table2, 1, False)
If IsNumeric(result) Then
result = "old"
End If
MsgBox result
Next cell
ErrorHandler:
If Err.Number = 1004 Then
result = "new"
End If
Resume Next
End Sub
答案 0 :(得分:0)
在application.match或application.vlookup上使用IsError,而不是application.worksheetfunction.vlookup。
dim result as variant
For Each cell In table1
result = "old"
If IsError(Application.match(cell, table2, 0)) then
result = "new"
end if
MsgBox result
cell.offset(0, 2) = result
Next cell