【问题标题】:VLOOKUP, For Each loop - write result to cellVLOOKUP,对于每个循环 - 将结果写入单元格
【发布时间】:2018-07-22 09:48:22
【问题描述】:

我在 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

【问题讨论】:

    标签: vba excel loops vlookup


    【解决方案1】:

    在 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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-03-09
      • 1970-01-01
      • 1970-01-01
      • 2021-11-06
      • 2023-03-27
      • 2020-04-18
      相关资源
      最近更新 更多