在循环vba中显示最小值

时间:2015-11-25 13:57:34

标签: vba excel-vba loops excel

我遇到问题,要显示循环中找到的最小值。 目标是尽可能找到最佳匹配,并在公司的消息框中显示

问题:我没有成功做的是在消息框中显示2计算差异最小的公司名称。目前,代码仅显示最后一家公司的名称。

见图:

enter image description here

参见代码:

Sub BestMatch()

    Dim resultCell      As Double
    Dim checkCell       As Double
    Dim checkCell2       As Double
    Dim bestDiff        As Double
    Dim bestDiff2        As Double
    Dim bestDiff3         As Double

    checkCell = Range("E2").Value
    checkCell2 = Range("E3").Value
    bestDiff = checkCell
    bestDiff2 = checkCell2

    For i = 1 To Range("C" & Rows.Count).End(xlUp).Row

        If (Range("A" & i).Value <= checkCell Or Range("A" & i).Value >= checkCell) And (Range("B" & i).Value <= checkCell2 Or Range("B" & i).Value >= checkCell2) Then

                If (checkCell - Range("A" & i).Value) <= bestDiff Or (checkCell - Range("A" & i).Value) >= bestDiff And (checkCell2 - Range("B" & i).Value) <= bestDiff2 Or (checkCell2 - Range("B" & i).Value) >= bestDiff2 Then

                        bestDiff3 = Application.WorksheetFunction.Min(Abs(checkCell - Range("A" & i)) + Abs(checkCell2 - Range("B" & i)))

                        resultCell = Range("C" & i)

                End If
            End If
        Next i

    MsgBox "Best match is in " & resultCell

    End Sub

1 个答案:

答案 0 :(得分:2)

您需要创建一个条件语句来比较每个循环的bestDiff3(基本上是自身)并检查最小的循环。

我在您的代码中添加了该测试语句,并修复了您的resultCell声明为Double,如果您希望返回String,则应该Company X

Sub CheckCell()

Dim resultCell As String 'fixed this to return string value of Company X
Dim CheckCell As Double
Dim checkCell2 As Double
Dim bestDiff As Double
Dim bestDiff2 As Double
Dim bestDiff3 As Double
Dim dLowValue As Double 'added as a variable to check for lowest value

CheckCell = Range("E2").Value
checkCell2 = Range("E3").Value
bestDiff = CheckCell
bestDiff2 = checkCell2
dLowValue = 1000 'set to arbitrary beginning number to test against

For i = 1 To Range("C" & Rows.Count).End(xlUp).Row

    If (Range("A" & i).Value <= CheckCell Or Range("A" & i).Value >= CheckCell) And (Range("B" & i).Value <= checkCell2 Or Range("B" & i).Value >= checkCell2) Then

            If (CheckCell - Range("A" & i).Value) <= bestDiff Or (CheckCell - Range("A" & i).Value) >= bestDiff And (checkCell2 - Range("B" & i).Value) <= bestDiff2 Or (checkCell2 - Range("B" & i).Value) >= bestDiff2 Then

                    bestDiff3 = Application.WorksheetFunction.Min(Abs(CheckCell - Range("A" & i)) + Abs(checkCell2 - Range("B" & i)))


                    If bestDiff3 < dLowValue Then

                        dLowValue = bestDiff3
                        resultCell = Range("C" & i)

                    End If

            End If
        End If
    Next i

MsgBox "Best match is in " & resultCell

End Sub