匹配错误438

时间:2014-02-21 19:16:00

标签: vba excel-vba excel

我无法让MATCH工作,请帮忙! 我一直在最后一行得到错误438 ...... 标题定义后只有一个数据点,'row'值变为2,loc设置为“A1:A2”。

提前致谢!

Dim loc As String
Dim row As Integer
Dim value As Integer

'Get current max rows in table
row = Cells.CurrentRegion.Rows.count
'Define the range as being all of A column to end of data
loc = "A1:A" & row

'lookFor is defined previously as some value to search for
value = ActiveSheet.Match(lookFor, ActiveSheet.range(loc), 0)

1 个答案:

答案 0 :(得分:1)

ActiveSheet.Match更改为Application.Match

value = Application.Match(lookFor, ActiveSheet.Range(loc), 0)

第一个提示:不要使用具有特殊VBA名称的变量,例如valuerow。请使用myValuelastrow之类的内容。

第二个提示:如果Match什么都没找到,就会返回错误。要处理它,请使用以下代码:

Dim myValue As Variant

myValue = ActiveSheet.Match(lookFor, ActiveSheet.Range(loc), 0)

If Not IsError(myValue) Then
    'do sth
End If

第三条提示:如果您需要在A列中找到最后一个非空行,建议您使用

Dim lastRow as Long
lastRow = Cells(Rows.Count, "A").End(xlUp).Row

代替

row = Cells.CurrentRegion.Rows.count

注意我宣布lastRow as Long。将Integer用于行变量是个不错的主意,因为Integer的最大值仅为32767

有关查找最后一行的详细信息,请参阅this @SiddharthRout's answer