簡體   English   中英

在VBA中使用具有可變查找位置的INDEX MATCH

[英]Using INDEX MATCH in VBA with Variable Lookup Locations

我在索引匹配中的查找條件內使用變量時遇到麻煩。 背景知識:我使用以下代碼將變量的值設置為B列中包含“當前”的任何單元格的行號:

Dim rowHeaderNum As Integer

    rowHeaderNum = 0

    On Error Resume Next
    rowHeaderNum = Application.Match("Current", ActiveSheet.Range("B:B"), 0)
    On Error GoTo 0

然后,我使用以下代碼將行“ rowHeaderNum”中單元格的列號存儲到另一個變量中,該行包含“ CurrentActual”值:

Dim currActColNum As Integer

currActColNum = 0
    currActColNum = Application.Match("CurrentActual", Rows(rowHeaderNum & ":" & rowHeaderNum), 0)

以下是我無法使用的“索引匹配”行:

Dim currActRev As Double

    currActRev = Application.Index(Columns(currActColNum), Application.Match("Gross Operating Profit", Columns("N:N"), 0))

currActRev將存儲美元金額。 Match函數將始終使用N列作為查找數組。 當我運行“ Index Match行時,

類型不匹配

調試器中的錯誤。

使用WorksheetFunction …

Application.MatchOn Error Resume Next不起作用,因為Application.Match不會引發異常,您需要改用WorksheetFunction.Match

根據文檔, WorksheetFunction.Match方法將返回Double因此您需要將Dim RowHeaderNum As Double

Dim RowHeaderNum As Double
'RowHeaderNum = 0 'not needed it is always 0 after dim

On Error Resume Next
RowHeaderNum = Application.WorksheetFunction.Match("Current", ActiveSheet.Range("B:B"), False)
On Error GoTo 0

此外,您需要檢查RowHeaderNum是否為0並停止進行操作,否則以下代碼將失敗,因為第0行不存在。

If RowHeaderNum = 0 Then
    MsgBox "'Current' not found."
    Exit Sub
End If

您需要在這里做完全一樣的事情

Dim CurrActColNum As Double
On Error Resume Next
CurrActColNum = Application.WorksheetFunction.Match("CurrentActual", Rows(RowHeaderNum), False)
On Error GoTo 0

If CurrActColNum = 0 Then
    MsgBox "'CurrentActual' not found."
    Exit Sub
End If

最后, WorksheetFunction.Index方法返回一個Variant而不是Double並且您在這里也需要錯誤處理。

Dim currActRev As Variant
On Error Resume Next
currActRev = Application.WorksheetFunction.Index(Columns(CurrActColNum), Application.WorksheetFunction.Match("Gross Operating Profit", Columns("N:N"), False))
On Error GoTo 0

Debug.Print currActRev 'print result in immediate window

使用Application …

請注意,您還可以使用Application.MatchApplication.Index (不帶WorksheetFunction ),但是不能使用On Error …並且必須使用IsError()檢查錯誤。 另外,還需要將變量聲明為Variant因為Application.Match可以返回錯字Double或類型Error

Dim RowHeaderNum As Variant
RowHeaderNum = Application.Match("Current", ActiveSheet.Range("B:B"), False)

If IsError(RowHeaderNum) Then
    MsgBox "'Current' not found."
    Exit Sub
End If

Dim CurrActColNum As Variant
CurrActColNum = Application.Match("CurrentActual", Rows(RowHeaderNum), False)

If IsError(CurrActColNum) Then
    MsgBox "'CurrentActual' not found."
    Exit Sub
End If


Dim currActRev As Variant, currMatch As Variant
currMatch = Application.Match("Gross Operating Profit", Columns("N:N"), False)
If Not IsError(currMatch) Then
    currActRev = Application.Index(Columns(CurrActColNum), currMatch)
End If

Debug.Print currActRev 'print result in immediate window

暫無
暫無

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

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