查找单元格中的最低值Excel VBA

时间:2015-05-26 14:57:24

标签: excel vba excel-vba

我是新手。我试图找到内部有多个值的单元格中的最低值。例如,

48
44.50
41.00
37.50

我想找到37.50。它的代码应该是什么?

由于

4 个答案:

答案 0 :(得分:1)

根据您发布的示例:

Sub FindMin()
   Dim s As String, CH As String
   Dim wf As WorksheetFunction
   Dim bry() As Double
   Set wf = Application.WorksheetFunction
   s = ActiveCell.Text

   CH = Chr(10)
   ary = Split(s, CH)
   ReDim bry(LBound(ary) To UBound(ary))

   For i = LBound(ary) To UBound(ary)
      bry(i) = CDbl(ary(i))
   Next i

   MsgBox wf.Min(bry)
End Sub

enter image description here

这假设单元格中的字段之间存在硬回车( ASCII-10 )。

修改#1:

要使其成为一个功能,删除子,替换

Public Function FindMin(r As Range) As Variant
   Dim s As String, CH As String
   Dim wf As WorksheetFunction
   Dim bry() As Double
   Set wf = Application.WorksheetFunction
   s = r.Text

   CH = Chr(10)
   ary = Split(s, CH)
   ReDim bry(LBound(ary) To UBound(ary))

   For i = LBound(ary) To UBound(ary)
      bry(i) = CDbl(ary(i))
   Next i

   FindMin = wf.Min(bry)
End Function

修改#2:

根据您的评论,以下是输入 vs 输出的示例:

enter image description here

请注意,所有值都在一个单元格中,并且值由硬返回而不是空格分隔。

答案 1 :(得分:0)

通过具有相同单元格的代码和" "作为破坏的分隔符

temp = Range("A1").Value

temp = Split(temp, " ")

Low = CInt(temp(0))

For i = 0 To UBound(temp) - 1
    If CInt(temp(i)) < Low Then Low = CInt(temp(i))
Next

Range("a2").Value = Low

如果它们在某个范围内,您可以使用公式

=MIN(A1:A4)

答案 2 :(得分:0)

这个问题与之前提出的问题非常接近: VBA/EXCEL: extract numbers from one cell that contained multiple values with comma

如果从该答案中获取代码并将逗号替换为分隔值的任何内容,则可以在VBA中访问它们。然后你可以编写代码来找到最小值。

答案 3 :(得分:0)

您可以创建一个宏来分割您选择的每个单元格的值,然后检查最高值。并快速检查以确保您没有解析所有空行(当您选择列时)。

下面的宏将设置下一列中的最高值。

Sub lowest()

    Dim Values As Variant
    Dim LowestValue As Double

    Dim a As Range

    Set a = Selection

    For Each Row In a.Rows

      For Each Cell In Row.Cells

        LowestValue = -1
        Values = Split(Cell.Value, Chr(10))

        For Each Value In Values

            If LowestValue = -1 Then
                LowestValue = Value
            ElseIf Value < LowestValue Then
                LowestValue = Value
            End If
        Next

        Cells(Cell.Row, Cell.Column + 1).Value = LowestValue
        If IsEmpty(Cell.Value) Then GoTo EndLoop

      Next Cell

    Next Row

EndLoop:

End Sub