VBA中获取最后结果的数组函数

huangapple go评论96阅读模式
英文:

Array function in VBA to get last result

问题

Sub Macro2()
    Name = "Ahmed Mohamed"
    x = WorksheetFunction.Lookup(2, (1 / Range("B1:B3") = Name), Range("C1:C3"))
    MsgBox (x)
End Sub
英文:

I have an array equation in an Excel sheet.

{=IFERROR(IF(=Sheet1!T1="approved", LOOKUP(2,1/(Sheet2!G9:G16=Sheet1!B1),Sheet2!H9:H16),""),"")}

This formula helps me get last result of the criteria instead of first.

I need it in VBA code and to assign its result to a variable called x.

My problem is with the lookup function because it is an array function.

Sub Macro2()
'
'
Name = "Ahmed Mohamed"

y = WorksheetFunction.Lookup(2, (1 / Range("B1:B3") = Name), Range("c1:c3"))
   
MsgBox (x)
   
End Sub

答案1

得分: 1

  • XLookupXMatch 有一个名为 search_mode 的参数,你可以将其设置为 -1 以获取最后一次出现。
Sub Lookup()

    Dim MyName As String: MyName = "Ahmed Mohamed"

    Dim x

    ' 使用 Worksheet.Evaluate

    x = ActiveSheet.Evaluate("LOOKUP(2,1/(B1:B3=""" & MyName & """),C1:C3)")

    If Not IsError(x) Then MsgBox x & "(Evaluate)"

    ' 如果你有 Microsoft 365:

    ' 使用 'Application.Index' 和 'Application.XMatch'

    With Application
        x = .Index(Range("C1:C3"), .XMatch(MyName, Range("B1:B3"), , -1))
    End With

    If Not IsError(x) Then MsgBox x & "(Index/XMatch)"

    ' 使用 'Application.XLookup'

    With Application
        x = .XLookup(MyName, Range("B1:B3"), Range("C1:C3"), , , -1)
    End With

    If Not IsError(x) Then MsgBox x & "(XLookup)"

End Sub
英文:

A VBA Lookup: Last Occurrence - XLookup and XMatch

  • XLookup and XMatch have this argument search_mode which you can set to -1 to get the last occurrence.

<!-- language: lang-vb -->

Sub Lookup()

    Dim MyName As String: MyName = &quot;Ahmed Mohamed&quot;
    
    Dim x
       
    &#39; Use Worksheet.Evaluate
    
    x = ActiveSheet.Evaluate(&quot;LOOKUP(2,1/(B1:B3=&quot;&quot;&quot; &amp; MyName &amp; &quot;&quot;&quot;),C1:C3)&quot;)
    
    If Not IsError(x) Then MsgBox x &amp; &quot;(Evaluate)&quot;
    
    &#39; If you have Microsoft 365:
    
    &#39; Use &#39;Application.Index&#39; and &#39;Application.XMatch&#39;
    
    With Application
        x = .Index(Range(&quot;C1:C3&quot;), .XMatch(MyName, Range(&quot;B1:B3&quot;), , -1))
    End With
    
    If Not IsError(x) Then MsgBox x &amp; &quot;(Index/XMatch)&quot;
   
    &#39; Use &#39;Application.XLookup&#39;
    
    With Application
        x = .XLookup(MyName, Range(&quot;B1:B3&quot;), Range(&quot;C1:C3&quot;), , , -1)
    End With
    
    If Not IsError(x) Then MsgBox x &amp; &quot;(XLookup)&quot;
   
End Sub

huangapple
  • 本文由 发表于 2023年3月7日 20:09:03
  • 转载请务必保留本文链接:https://go.coder-hub.com/75661795.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定