簡體   English   中英

在Excel VBA VLookup函數中使用索引和匹配

[英]Using Index and Match in Excel VBA VLookup function

我有一個excel公式,我經常使用它做一個VLookup 它有一個嵌入的Index/Match ,它給出“M”列中的最后一個數值。
工作表公式是這樣的:

=VLOOKUP(INDEX($M$10:$M75,MATCH(9.99999999999999E+307,$M$10:$M75)),Data,4)

單元格$M75是此公式所在行的單元格。列M中有數字,非數字和空白單元格,但我想要的ID始終為數字。

所以我試着寫一個自定義函數,讓我簡單地寫=current()

這是我有的:

Function Current()
  Dim LookupRange As Variant
  Dim indexVar As Variant
  LookupRange = Range("$M$1:M" & ActiveCell.Row)
  indexVar = Application.Index(Range(LookupRange), Application.Match(9.99999999999999E+307, Range(LookupRange)))
  Current = Application.WorksheetFunction.VLookup(indexVar, Worksheets("Info").Range("Data"), 4)
End Function

我嘗試使用不同的變量類型(String,Long,Variant),但我似乎無法使函數工作。
我不知道這是否足夠信息,但任何人都可以看到我是否遺漏了什么?
我只得到#VALUE!
在Windows 7上使用Excel 2013

此代碼存在一些與您的描述不一致的問題。

  • LookupRange是一個變體數組。 當我測試它時,它在indexVar的賦值中引發了1004 Method 'Range' of object '_Global' failed錯誤的1004 Method 'Range' of object '_Global' failed
  • 如果我根據你的評論Dim LookupRange As String ,我也會收到Type Mismatch錯誤。

由於LookupRange應該是一個范圍,我將其聲明為范圍,並在賦值語句中使用Set關鍵字。

Set lookupRange = Range("$M$10:$M" & ActiveCell.Row)
  • 您對lookupRange的分配可能存在拼寫錯誤。 在你的公式中,最初使用$M$1 ,但在函數中你使用$M$10

如果您以$M$10開始此范圍,並嘗試在第1-9行之間的任何單元格中評估公式,則會出現錯誤。

在相關的說明中, 如果 lookupRange 中沒有數值 ,則這將返回錯誤,例如,將單元格M2 Current()置於M1:M2的查找范圍內,其中我沒有數字數據。

在此輸入圖像描述

我不確定你想怎么處理這個,但我的答案包括一種避免這種錯誤的方法。 您可以根據需要進行修改。 最后:

  • 依賴ActiveCell.Row似乎是一個壞主意,因為這個公式可能會重新計算不良結果。

相反,將其設為公式的必需參數,然后可以從工作表調用,如: =Current(Row())

把它們放在一起,我認為這應該工作,我提供了一個示例/轉義匹配未找到錯誤。

Public Function Current(r As Long)
    Const bigNumber As Double = 9.99999999999999E+307
    Dim wsInfo As Worksheet: Set wsInfo = Worksheets("Info")
    Dim lookupRange As Range
    Dim indexVar As Long
    Dim myVal As Variant

    Set lookupRange = Range("$M$1:$M" & r)
    If Not Application.WorksheetFunction.Sum(lookupRange) = 0 Then
        indexVar = Application.Index(lookupRange, Application.Match(bigNumber, lookupRange))
        myVal = Application.WorksheetFunction.VLookup(indexVar, wsInfo.Range("Data"), 4)
    Else:
        myVal = "No numbers found in: " & lookupRange.Address
    End If
    Current = myVal

End Function

評論的更新

您可以在變量聲明之前添加Application.Volatile 鏈接 這應該強制重新計算:

只要在工作表上的任何單元格中進行計算。

但是,當其他工作表上的值(例如,您的Worksheets("Info")是另一個工作表)更改時,這不會強制計算。

要在每次激活包含=Current(Row())函數的工作表時強制重新計算,可以將其放在工作表的代碼模塊中:

Private Sub Worksheet_Activate()
    Me.Calculate
End Sub

這可能就像你可以得到的那樣 - 復制本機VLOOKUP功能而不實際使用VLOOKUP公式。

補充筆記:

偏好正確/強類型變量,我將indexVar as Long聲明indexVar as Long並為9.99999999999999E+307創建一個雙精度變量(這樣更容易使用)。 我還創建了一個工作表對象變量,我再次發現它們更容易使用。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM