使用 Match 功能时出现错误,我找不到问题,请您帮帮我好吗?
我还想知道我们是否可以使用 Find 功能做同样的事情。
我已将范围命名为 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)
,我没有类型不匹配了,但是另一个错误,Run time error '1004' Unable to get the Match propertyof the WorksheetFunction class
仅供引用,如果它可能有帮助,我打开了另一个工作簿,实际上我的工作簿打开了另一个工作簿,但是正如您在我的代码中看到的那样,我有 ws.data 的引用,所以我不知道事实是否打开另一个工作簿会导致此错误或什么
最佳答案
正如评论中所解释的,当您将范围设置为值时,您正在执行一个 2-dim 数组,其中 Match
不会支持。而是重写您的代码,如下所示:
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使用 find 功能可能会很有用:
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
下面是一个 match 与一个方法一起使用的例子,如果没有找到就处理错误:
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
关于excel - Match函数返回类型不匹配的问题(VBA EXCEL),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54871068/