访问最大功能:返回10个字段中的第二个最高值

问题描述 投票:0回答:1

我没有编写VBA代码的经验,但我可以遵循逻辑。

感谢大家的帮助!

我找到了一个VBA代码,它计算了一系列10个字段(临时数组和两个类别)中的第二高值。它实际上很有效,除非第一个字段是零或所有字段都包含零。

enter image description here

Function Maximum (ParamArray FieldArray() As Variant)
' Declare the two local variables.
Dim I As Integer
Dim currentVal As Variant
Dim secondHighest As Variant

' Set the variable currentVal equal to the array of values.
  currentVal = FieldArray (0)

' Cycle through each value from the row to find the largest.

    Dim tmpArray
    For I = 0 To UBound(FieldArray)
        If FieldArray(I) > currentVal Then
        currentVal = FieldArray(I)
        End If
    Next

tmpArray = Filter (FieldArray, currentVal, False, vbTextCompare)
'This will fill the tmpArray with all your array values EXCEPT the highest one.

    secondHighest = tmpArray(0)
        For I = 0 To UBound(tmpArray)
        If tmpArray(I) > secondHighest Then
        secondHighest = tmpArray(I)
    End If
    Next

' Return the maximum value found.
Maximum = secondHighest

' Expr1: Maximum ([nPP1CSF],[nPP2CSF],[nPP3CSF],[nPP4CSF],[nPP5CSF],[nPP6CSF],[nPP7CSF],[nPP8CSF],[nPP9CSF],[nPP0CSF])

End Function

感谢您的及时回复!我现在有错误“类型不匹配”。它发生在“If Not(Not tmpArray)Then”行

access-vba
1个回答
0
投票

您的tmpArray可以包含0项。你应该检查一下。

说起来容易做起来难,我用this trick进行测试

(从理论上讲,如果有人没有正确使用它,你的FieldArray也可以包含0项)。

Function Maximum (ParamArray FieldArray() As Variant)
' Declare the two local variables.
Dim I As Integer
Dim currentVal As Variant
Dim secondHighest As Variant
If (Not FieldArray) = -1 Then Exit Function 'If nothing gets entered, do nothing
' Set the variable currentVal equal to the array of values.
  currentVal = FieldArray (0)

' Cycle through each value from the row to find the largest.

    Dim tmpArray
    For I = 0 To UBound(FieldArray)
        If FieldArray(I) > currentVal Then
        currentVal = FieldArray(I)
        End If
    Next

tmpArray = Filter (FieldArray, currentVal, False, vbTextCompare)
'This will fill the tmpArray with all your array values EXCEPT the highest one.
If Not (Not tmpArray) Then
    secondHighest = tmpArray(0)
        For I = 0 To UBound(tmpArray)
        If tmpArray(I) > secondHighest Then
        secondHighest = tmpArray(I)
    End If
    Next
End If
' Return the maximum value found.
Maximum = secondHighest

' Expr1: Maximum ([nPP1CSF],[nPP2CSF],[nPP3CSF],[nPP4CSF],[nPP5CSF],[nPP6CSF],[nPP7CSF],[nPP8CSF],[nPP9CSF],[nPP0CSF])

End Function
© www.soinside.com 2019 - 2024. All rights reserved.