简体   繁体   English

在VBA中使用Match比较单元格

[英]Comparing cells using match in vba

I am trying to compare two columns of cells in vba using the match function. 我正在尝试使用match函数比较vba中的两列单元格。 I am comparing the second column against values in the first and copying and pasting the values that aren't found to another column. 我正在将第二列与第一列中的值进行比较,然后将未找到的值复制并粘贴到另一列中。 I am doing the same with the second against the first as well. 我也要对第二个做同样的事情。 For some reason when I try to run this it says that it cannot get the match property of the worksheet function class and I am really confused as to why I am receiving this error. 由于某些原因,当我尝试运行此命令时,它说它无法获取工作表函数类的match属性,而对于为什么收到此错误,我确实感到困惑。 I have pasted the code below. 我已经粘贴了下面的代码。 Any help with this issue would be greatly appreciated. 任何与此问题的帮助将不胜感激。

Set PrevMonth = Sheet13.Range(Range("A2"), Range("A2").End(xlDown))
Set currMonth = Sheet13.Range(Range("B2"), Range("B2").End(xlDown))
Count = 2

For i = 2 To PrevMonth.Rows.Count
match = Application.WorksheetFunction.match(Cells(i, 1), currMonth, 0)
If WorksheetFunction.IsNA(match) = True Then
Sheet13.Cells(i, 1).Cut
Sheet13.Cells(Count, 3).Paste
Count = Count + 1
End If
Next i

For i = 2 To currMonth.Rows.Count
match = WorksheetFunction.match(Cells(i, 1), PrevMonth, 0)
If WorksheetFunction.IsNA(match) = True Then
Sheet13.Cells(i, 1).Cut
Sheet13.Cells(Count, 4).Paste
Count = Count + 1
End If
Next i

Can you try using 你可以尝试使用

Application.Match(Cells(i, 1), currMonth, 0)

I know this should have been a comment...but I'm unable to comment as I'm below 50 Rep... 我知道这应该是一条评论...但是我无法发表评论,因为我的代表低于50岁...

In my experience the "cannot get 'X' property of the worksheet function class" error is indicative that a poor argument has been passed to the worksheet function itself. 以我的经验,“无法获取工作表函数类的'X'属性”错误表明一个错误的参数已传递给工作表函数本身。 In your case the arguments are: Cells(i, 1), currMonth. 在您的情况下,参数为:Cells(i,1),currMonth。 This likely means one of those ranges are inaccessible. 这可能意味着这些范围之一不可访问。 If I had to guess, you want to be passing sheet13.cells(i,1). 如果我不得不猜测,您想传递sheet13.cells(i,1)。 I'd recommend a 'with sheet13' statement for this whole segment of code. 对于整个这段代码,我建议使用“ with sheet13”语句。 WorksheetFunction.Match in particular will throw that error if a match can't be found (VB doesn't work with the #N/A return value). 如果找不到匹配项,则WorksheetFunction.Match特别会抛出该错误(VB不适用于#N / A返回值)。 Using a WorksheetFunction.CountIf > 0 can ensure there is a viable match within the range. 使用WorksheetFunction.CountIf> 0可以确保在该范围内存在可行的匹配项。

Also, Range("A2").End(xlDown) will result in the last cell of the column if there is no data after A2. 同样,如果A2之后没有数据,则Range(“ A2”)。End(xlDown)将导致列的最后一个单元格。 This is generally unfavorable behavior. 这通常是不利的行为。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM