[英]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.Match
和On 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.Match
和Application.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.