英文:
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
XLookup
和XMatch
有一个名为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
andXMatch
have this argumentsearch_mode
which you can set to-1
to get the last occurrence.
<!-- language: lang-vb -->
Sub Lookup()
Dim MyName As String: MyName = "Ahmed Mohamed"
Dim x
' Use Worksheet.Evaluate
x = ActiveSheet.Evaluate("LOOKUP(2,1/(B1:B3=""" & MyName & """),C1:C3)")
If Not IsError(x) Then MsgBox x & "(Evaluate)"
' If you have Microsoft 365:
' Use 'Application.Index' and '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)"
' Use '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
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论