2017-09-22 234 views
3

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

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

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

这应该是我的结果:

1100 
1290 
1500 
2030 
2100 
2500 
3000 

结果我已现在在那里(3000和3005之间的差具有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 
+2

按您自己的规范,3005应该是在名单上,因为3005和1290和3005和1500之间的差异之间的差异都较大比3%...请重新审视您的规定 – jsotola

+0

@ Jonathon-Sidwell,它wou ld对这篇文章的任何读者都有帮助,如果你至少可以描述你使用你的查询的内容。因为指定通缉方法似乎有些困难。 –

回答

1

@Jonathon当我通过你的代码,发现您需要选择列“d”值像,

如果选择值,则没有任何价值的任何3%附近的选择选定的值

和选择标准从去底部向上落入第一把它作为你在建议(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 

“子到此结束 ‘’”“”

+1

始终使用完全合格的范围参考,例如'Dim ws As WorkSheet'后面跟着'Set ws = ThisWorkBook.WorkSheets(“MySheetName”)'。然后,您可以精确地参考'ws.Cells(i + 1,“D”)',而不是'Cells'。 –

+0

通过内部颜色索引而不是使用额外列来标记排除值是个不错的主意。 –

+0

您的ComVal声明为字符串将导致类型错误。 –