用户窗体组合框计算不正确

时间:2019-06-24 18:57:10

标签: excel vba userform

我的数学或代码有问题,导致组合框值的计算不准确。如果总和应为100%,我将得到80%或125%。 有11个组合框,可以是1-5或不适用。 NA的值为0。 这是我正在使用的代码:

Private Sub CommandButton1_Click()

Dim c As Control, n1 As Long, n2 As Long, n3 As Long, n4 As Long, n5 As Long
n1 = 0
n2 = 0
n3 = 0
n4 = 0
n5 = 0

For Each c In Me.Controls
    If TypeName(c) = "ComboBox" Then
        If c.Value = "1" Then n1 = n1 + 1
        If c.Value = "2" Then n2 = n2 + 2
        If c.Value = "3" Then n3 = n3 + 3
        If c.Value = "4" Then n4 = n4 + 4
        If c.Value = "5" Then n5 = n5 + 5
    End If
Next c

TXTCount = (n1 + n2 + n3 + n4 + n5)

For Each c In Me.Controls
    If TypeName(c) = "ComboBox" Then
        If c.Value = "1" Then n1 = n1 + 1
        If c.Value = "2" Then n2 = n2 + 1
        If c.Value = "3" Then n3 = n3 + 1
        If c.Value = "4" Then n4 = n4 + 1
        If c.Value = "5" Then n5 = n5 + 1
    End If
Next c

TXTPotential = (n1 + n2 + n3 + n4 + n5 * 4)

TXTScore = TXTCount.Value / TXTPotential.Value

(结果可能会超过100%,并给出4分和5分以上的得分)

1 个答案:

答案 0 :(得分:0)

我认为这是操作顺序问题。

尝试TXTPotential = ((n1 + n2 + n3 + n4 + n5) * 4)

编辑: 我更改了您的一些变量名,并删除了n1,n2等,如果您要分别对每个变量进行操作,则可以将它们保留在其中,但是在此代码块中,不需要那么多。

    Dim target_control As Control
    Dim control_value As Integer
    Dim control_count As Integer


    control_value = 0
    control_count = 0

    For Each target_control In Me.Controls
        If TypeName(target_control) = "ComboBox" Then
            If Not target_control.Value = "NA" Then
                control_value = control_value + cint(target_control.Value)
                control_count = control_count + 1
            End If
        End If
    Next

    TXTPotential = control_count * 4 'I'm guessing

    TXTScore = control_value / TXTPotential

编辑2:

这应该忽略0s