使用“匹配”功能时出现错误,我找不到问题,请您帮帮我吗? 我也想知道我们是否可以使用“查找”功能来做同样的事情。
我已经命名了名为DataListName
的范围,它位于工作表“数据”(ID名称)或“数据库”(工作表名称)中
DataListName代表列C
DataListName =数据库!$ C:$ C
我正在尝试在C列中找到行ListABC
这是我的代码:
Dim ListNameArr As Variant
Dim LookupRow As Long
Dim ListNameValue As String
ListNameValue ="ListABC"
With wsData
ListNameArr = .Range("DataListName").Value
LookupRow = Application.WorksheetFunction.Match(ListNameValue, ListNameArr, 0)
end with
任何人都可以向我解释错误在哪里?如果我可以使用Find方法做同样的事情,怎么做和哪个更好?
编辑:
如果我按照建议更换
LookupRow = Application.WorksheetFunction.Match(ListNameValue, ListNameArr, 0)
作者
LookupRow = Application.WorksheetFunction.Match(ListNameValue, .Range("DataListName"), 0)
,我不再有类型不匹配的问题,而是另一个错误
运行时错误'1004'无法获取 WorksheetFunction类
仅供参考(如果可能有帮助),我打开了另一个工作簿,实际上我的工作簿也打开了另一个工作簿,但是正如您在代码中所看到的那样,我有ws.data的引用,所以我不知道如果打开另一个工作簿的事实导致此错误或什么原因
答案 0 :(得分:1)
如注释中所述,将范围设置为value时,您正在执行Match
不支持的2维数组。而是如下重写代码:
Dim ListNameArr As Range, LookupRow As Long, ListNameValue As String
ListNameValue = "ListABC"
Set ListNameArr = wsData.Range("DataListName")
LookupRow = Application.WorksheetFunction.Match(ListNameValue, ListNameArr, 0)
在这里,您可以利用Find
作为C列并返回该行。如果希望更改搜索范围,希望可以进行调整。
LookupRow = ListNameArr.Cells.Find(What:=ListNameValue, _
LookIn:=xlFormulas, _
LookAt:=xlPart, _
SearchOrder:=xlByRows, _
SearchDirection:=xlNext, _
MatchCase:=False, _
SearchFormat:=False).Row
Here's some other examples使用查找功能可能会有用:
Sub Find_Example_WithLoop()
Dim CL As Range, FirstFoundAddress As String
Dim WS As Worksheet: Set WS = ActiveSheet
'FIND SYNTAX By PGCodeRider
'LOOKIN: xlFormulas , xlValues , or xlNotes
'LookAT: xlWhole or XlPart
'SearchOrder: xlByRows or xlByColumns
'SearchDirection: xlNext or xlPrevious
'MatchCase: True or False
'FindNext - Continues a search that was begun with the Find method. Finds the next cell that matches those same conditions.
' Find first instance on sheet
Set CL = WS.Cells.Find(What:="BOOOOM", _
After:=WS.Cells(1, 1), _
LookIn:=xlFormulas, _
LookAt:=xlPart, _
SearchOrder:=xlByRows, _
SearchDirection:=xlNext, _
MatchCase:=False, _
SearchFormat:=False)
If Not CL Is Nothing Then
' if found, remember location, else ends if-statement
FirstFoundAddress = CL.Address
Do
'DO SOMETHING!!
' find next instance
Set CL = WS.Cells.FindNext(After:=CL)
' repeat until finds original cell
Loop Until FirstFoundAddress = CL.Address
End If
Next
End Sub
以下是匹配的示例,该方法与找不到错误的方法一起使用:
Sub matchExample()
Dim text2match As String: text2match = "matchME"
Dim rng2Match As Range: Set rng2Match = Range("A:A")
'should return an integer
On Error GoTo notGOOD
MsgBox Application.WorksheetFunction.Match(text2match, rng2Match, 0)
On Error GoTo 0
Exit Sub
notGOOD:
MsgBox "Couldn't find " & text2match
End Sub
答案 1 :(得分:0)
我使用以下代码绕过了错误
Dim Var As Variant
Var = Application.Match(ListNameValue, .Range("DataListName"), 0)
If Not IsError(Var) Then
LookupRow = CLng(Var)
Else
LookupRow = 0
如果结束