是否可以将InStr()与Application.Vlookup()结合使用?

时间:2018-09-17 17:19:06

标签: excel vba formula vlookup

我目前有一个With语句,它将一个单元格的值与一系列单元格进行比较,并且InStr()返回true,然后将cell.Value标记为“ Yes"”,否则将{{ 1}}。

这是场景。假设我正在检查"No"的值,它是A2。我正在将111与一系列其他单元格进行比较,并且应该匹配的字段为111,因为其中包含111, 222, 333。我下面的第一组代码对此有效,但是速度很慢。我希望有一个更快的方法,我认为我可以使用公式来做到这一点,但是在vlookup中使用111而不是True却无法正常工作。

代码如下:

False

问题在于它有点慢。我的应用程序大约需要5分钟才能运行。我希望将With inv_twcg_ws For Each cell In .Range("A2:A" & .Cells(Rows.Count, "A").End(xlUp).Row) For Each cellx In report_rng If InStr(cellx.Value, cell.Value) Then cell.Offset(0, 6).Value = "Yes" Exit For End If cell.Offset(0, 6).Value = "No" Next cellx Next cell End With InStr()结合起来以尝试加快公式的速度。这可能吗?

这是我当前的Vlookup,但是使用Application.Vlookup()并不能满足我的需要...

True

1 个答案:

答案 0 :(得分:6)

使用变量数组:

Dim report_ws As Worksheet
Set report_ws = report_wb.Worksheets(1)

Dim report_rng As Variant
report_rng = report_ws.Range("B2:B" & last_row)

Dim inv_twcg_ws As Worksheet
Set inv_twcg_ws = Worksheets("Sheet1") ' change to your sheet




With inv_twcg_ws
    Dim lkup_rng As Variant
    lkup_rng = .Range("A2:A" & .Cells(Rows.Count, "A").End(xlUp).Row).Value

    Dim otpt As Variant
    ReDim otpt(1 To UBound(lkup_rng, 1), 1 To 1) As Variant

    Dim i As Long
    For i = LBound(lkup_rng, 1) To UBound(lkup_rng, 1)
        otpt(i,1) = "No"
        Dim j As Long
        For j = LBound(report_rng, 1) To UBound(report_rng, 1)
            If InStr(report_rng(j, 1), lkup_rng(i, 1)) Then
                otpt(i,1) = "Yes"
                Exit For
            End If
        Next j
    Next i

    .Range("G2").Resize(UBound(otpt, 1)).Value = otpt
End With