在第1列中查找多个匹配值,然后从第3列获取其MIN对应值

时间:2016-01-14 19:48:45

标签: vba excel-vba excel

我试图找到在第1列中出现多次的值,然后从第3列中获取它们的MIN对应值。例如,如果第1列有3个匹配值124L,它们在第3列中的对应值是120 ,90和60,然后用60覆盖匹配值的第3列。所以在一天结束时,我的所有124L应该在第3列中有60个。

我很感激任何帮助或方向,目前我特别难以搜索多个匹配值。谢谢。以下是即使发布后也感到羞耻的代码......

  Sub minFinder()

  'declare variables
   Dim minCartMx As Long, multiLocsCartMxFound As Long
   Dim searchMultiLocs As Range, foundMultiLocs As Range
   Dim FinalRow As Long
   FinalRow = Cells(Rows.Count, 1).End(xlUp).Row
    For i = 2 To FinalRow
  'search multiple occurances of values in column 1
   Set searchMultiLocs = Cells(i, 1)
   For Each searchMultiLocs In searchMultiLocs

  'I dont think this works but am trying to get values of corresponding  
   'to foundMultiLocs in column 3 (cells(i,3)

  Set multiLocsCartMxFound = searchMultiLocs.Find(what:=searchMultiLocs, 
  LookIn:=xlWhole, _ searchorder:=xlByRows, searchDirection:=xlNext, _ 
  MatchCase:=False, searchformat:=False)


  'determine the minumum value of column 3 of the foundMultiLocs
  minCartMx = Application.WorksheetFunction.Min(multiLocsCartMxFound)

' overwrite the column 3 of the matching values with MIN
  minCartMx = Cells(i, 3)


 End Sub

在这里输入代码

2 个答案:

答案 0 :(得分:1)

Find仅返回单个单元格。请改用Evaluate来查找最小值。此示例返回C列中的最小值,其中A列为"value"

minValue = Application.Evaluate("min(if(A1:A10 = ""value"",  C1:C10, """"))")

此外,在代码的最后一行,您的操作数将被翻转。你打算写Cells(i,3) = minCartmx

答案 1 :(得分:1)

在Vba:

Sub minFinder()
Dim ws As Worksheet
Dim rng As Range
Dim minRng As Range
Dim cel As Range

Set ws = Sheets("Sheet5") 'Change to your sheet

With ws
    Set rng = .Range(.Cells(2, 1), .Cells(.Rows.Count, 1).End(xlUp))
    Set minRng = .Range(.Cells(2, 3), .Cells(.Rows.Count, 3).End(xlUp))
End With
For Each cel In rng
    cel.Offset(, 2).Value = ws.Evaluate("=MIN(IF(" & cel.Address(0, 0) & "=" & rng.Address(0, 0) & "," & minRng.Address(0, 0) & "))")
Next cel


End Sub

但是您可以使用代码中的公式轻松完成此操作。

在空栏中放置:

=MIN(IF(A2=$A$2:$A$7,$C$2:$C$7))

这是一个数组公式,必须使用ctrl-Shift-Enter确认。

enter image description here

然后,这只是复制和粘贴值的问题。