Search code examples
excelvbauserform

How to calculate score based on userform combobox responses dynamically


I have a userform with 7 comboboxes that have the option of Yes, No, Partially and N/A. Based on the response in each of the box I have a textbox that populates the overall score.

Yes = 1,
Partially = 0.5,
No = 0 and
NA = 0.

I have the code that calculates based on the combobox responses and if I simply divide by the total boxes (7) it calculates however not all forms will have 7 responses (NA is an option but is then basically doesn't count for or against them). So I need to figure out how to divide the total score by the total responses. I'm sure it is super easy but I am not struggling to figure it out.

This is the code I current have in there that does not give me the correct %

TXTScore = Format((nYes + nPartial * 0.5) / nYes + nPartial + nNo, "Percent")
Private Sub CommandButton1_Click()

Dim c As Control, nYes As Long, nPartial As Long, nNo As Long


For Each c In Me.Controls
    If TypeName(c) = "ComboBox" Then
        If c.Value = "Yes" Then nYes = nYes + 1
        If c.Value = "Partially" Then nPartial = nPartial + 1
        If c.Value = "No" Then nNo = nNo + 1
    End If
Next c

TXTScore = Format((nYes + nPartial * 0.5) / nYes + nPartial + nNo, "Percent")
End Sub

For example - 6 Yes response and 1 NA would = 100%, 5 Yes responses, 1 Partially and 1 NA would equal 92%


Solution

  • You should count NA also (and add some brackets, I think)

    Private Sub CommandButton1_Click()
    
    Dim c As Control, nYes As Long, nPartial As Long, nNo As Long, nNA As Long
    nYes = 0
    nPartial = 0
    nNo = 0
    nNA = 0
    
    
    For Each c In Me.Controls
        If TypeName(c) = "ComboBox" Then
            If c.Value = "Yes" Then nYes = nYes + 1
            If c.Value = "Partially" Then nPartial = nPartial + 1
            If c.Value = "No" Then nNo = nNo + 1
            If c.Value = "NA" Then nNA = nNA + 1
        End If
    Next c
    
    TXTScore = Format((nYes + nPartial * 0.5) / (nYes + nPartial + nNo + nNA), "Percent")
    End Sub