【发布时间】:2021-06-10 18:34:51
【问题描述】:
我正在尝试开发一个通用函数来查找范围内多个条件的匹配项。根据我在 FastExcel 的一篇文章中找到的例程,当我对函数中的范围进行硬编码时,我可以使用以下代码。但是,如果我尝试传入范围(在 ParamArray 中),我会得到:
- 错误:如果我将 aRange 调暗为 Range,然后将 aRange = args(0) 调暗,或者
- 错误:“需要对象”,Dim aRange 作为 Variant,vArr Dim 作为 Variant,然后 vArr = aRange.Value2
这是我的代码:
Sub Test_FindCriteria()
Dim lrow As Long
lrow = FindCriteria(ActiveSheet.Range("a1:f100"), 1, "Ncompass", 3, "7.2", 4, "ncomphorizontrc", 5, "V85")
End Sub
Function FindCriteria(ParamArray args() As Variant) As Long
' Find row in range where multiple conditions are true
' Arg(0) = Range to search
' Remaing args are pairs where 1st is the column number (relative to Range) and 2nd is the item to be matched
' Arg(1) = 1st Column number to search for Match Item 1
' Arg(2) = match item 1 (in Range(,Arg(1))
' Arg(3) = 2nd Column number to search for Match Item 2
' Arg(4) = match item 2 (in Range(,Arg(3))
' Arg(n-1) = (n/2)th Column number to search for Match Item
' Arg(n) = match item n/2 (in Range(,Arg(n-1))
Dim vArr As Variant
Dim i As Integer
Dim j As Long
Dim k As Long
' Dim aRange As Range 'Gives Error Object Variable not set
Dim aRange As Variant
aRange = args(0) 'Gives Error: "Object Variable Not Set" if Dim aRange as Range
' bfound = False
' dTime = MicroTimer
vArr = aRange.Value2 'Gives Error: "Object Required" with Dim aRange As Variant
' vArr = ActiveSheet.Range("a1:f100").Value2 'Works when Range is declared in Function
j = LBound(vArr)
k = 0
Do
Do
k = k + 1
For i = 1 To UBound(args) Step 2
If vArr(j, args(i)) = args(i + 1) Then
bfound = True
Else
bfound = False
Exit Do
End If
Next i
Loop While False
j = j + 1
Loop While j < UBound(vArr) And Not bfound
Debug.Print "Found at " & k
FindCriteria = k 'could just use (j - LBound(vArr)) instead of k
End Function
如何使它在 Range 中传递给函数?谢谢!
【问题讨论】:
-
你应该这样做
Function FindCriteria(rng as range, ParamArray args() As Variant) As Long -
除了Scott Craner 的advice 对象,比如范围,还需要
set关键字。所以Set aRange = ... -
感谢 Scott 和 Warcupine。感谢您的快速帮助。我在与 Warcupine 差不多的时间发现了我的错误(省略了 Set),并在我对自己的回答中发布了更正的版本。