Excel VBA – 比较同一列中的行

我是新的Excel VBA,我有一个任务,我需要使用VBA来完成。 我正在寻找比较同一列中的值。 我想开始与最后一行的比较,并向上移动。 筛选条件是当前和最后一个数字之间的差值大于3%,然后将该值复制并粘贴到另一行。 一旦复制并粘贴一个值,在检查3%的差异时,应该将数据中的值与先前的复制粘贴值进行比较。 下面的例子。 提前致谢。

例如,如果我的数据范围如下所示

1100 1285 1290 3005 1500 2020 2030 2040 2050 2060 2070 2080 2100 2500 3000 

这应该是我的结果:

 1100 1290 1500 2030 2100 2500 3000 

我现在的结果有3005个(3000和3005之间的差异小于3%(3005/3000),因此3005不应该在列表中),当它不应该在列表中。

 1100 1290 3005 1500 2030 2100 2500 3000 

这是我目前的代码。 提前致谢。

 Sub main2() Dim row_a As Long Dim row_b As Long Dim l_2 row_b = Range("D5000").End(xlUp).Row Cells(row_b, "d").Copy Cells(row_b, "P") l_2 = row_b - 1 For i = row_b To 3 Step -1 a = Cells(row_b, "d").Value For j = l_2 To 3 Step -1 If a / Cells(j, "d") <= 0.97 Or a / Cells(j, "d") >= 1.03 Then Cells(j, "d").Copy Cells(j, "p") a = Cells(j, "d").Value End If Next j Next i End Sub 

@Jonathon当我浏览你的代码,发现你需要在列“D”中select值,

如果select了值,则没有任何值select接近任何选定值的3%

而select标准则是从最底层到最高层,如你所build议的(3000一3005问题)

并将所有选定的值粘贴到“P”列中

如果它是正确的,然后通过下面的代码,它满足你的条件,按照问题

“”“”“”“”“”“”“”“”“”“”“”“”“”“”“”“”“”“”“”“”“”“”“”“”“” '''''''''''''''''''代码从这里开始

 Sub Filter3Per() Dim LastRow As Integer Dim ComVal As String '''''''''Apply filter on columun with loop as per criteria 'Read last Row from D column LastRow = Cells(Rows.Count, "D").End(xlUp).Row 'Clear format color of column D Range("D:D").Interior.ColorIndex = -4142 '''Clear P column Range("P:P").ClearContents 'Loop Goes from botttom to top 3 row For i = LastRow - 1 To 1 Step -1 'Read compvalue ComVal = Cells(i + 1, "D").Value 'Check for color If Cells(i + 1, "D").Interior.ColorIndex <> 3 Then 'Loop to Check as Criteria For j = i To 1 Step -1 'Critera If ComVal / Cells(j, "D") <= 0.97 Or ComVal / Cells(j, "D") >= 1.03 Then Else Cells(j, "D").Interior.ColorIndex = 3 End If Next End If Next ''''''''Apply filter on columun with loop as per criteria End here '''''''''''''''Collect value'''''''''''''''''''' '''Clear P column Range("P:P").ClearContents For i = 1 To LastRow If Cells(i, "D").Interior.ColorIndex <> 3 Then Cells(i, "P").Value = Cells(i, "D") 'add value in p Column End If Next '''''''''''Collect value end here End Sub 

'在这里结束'''''