如何在VBA用户表单中计算具有多个组合框的百分比

时间:2017-10-10 12:44:48

标签: excel vba excel-vba combobox calculated-field

您好我需要在VBA中为用户形式提供多页的百分比分数。 如下所示 enter image description here

我按如下方式格式化了组合框:

 Private Sub UserForm_Initialize()
 With Cbx1_1
.AddItem "N/A"
.AddItem "Yes"
.AddItem "No"
 End With

With Cbx1_2
.AddItem "N/A"
.AddItem "Yes"
.AddItem "No"
End With

With Cbx1_3
.AddItem "N/A"
.AddItem "Yes"
.AddItem "No"
End With

With Cbx1_4
.AddItem "N/A"
.AddItem "Yes"
.AddItem "No"
 End With
 OUTBX.Value = " "
 End Sub

现在回答问题后出现问题,我希望包含一个名为"计算"的按钮。这将导致" ResultBx"这将等于67%。

这个想法是计算看起来像这样:

 ResultBx.Value=(COUNTIF(Range(Cbx1_1,Cbx1_2,Cbx1_3,Cbx1_4),"=Yes"))/
 ((COUNTA(Range(Cbx1_1,Cbx1_2,Cbx1_3,Cbx1_4)))-(COUNTIF((Range 
 (Cbx1_1,Cbx1_2,Cbx1_3,Cbx1_4)),"=N/A")))

我知道我在这里包含Excel代码,但我需要"转换"它到VBA

有人可以帮忙吗?

1 个答案:

答案 0 :(得分:1)

假设您的按钮名为CommandButton1

Private Sub CommandButton1_Click()
Dim a As Long, b As Long

a = IIf(cbx1_1.Value = "Yes", 1, 0) + IIf(cbx1_2.Value = "Yes", 1, 0) + IIf(cbx1_3.Value = "Yes", 1, 0) + IIf(cbx1_4.Value = "Yes", 1, 0)
b = 4 - IIf(cbx1_1.Value = "N/A", 1, 0) - IIf(cbx1_2.Value = "N/A", 1, 0) - IIf(cbx1_3.Value = "N/A", 1, 0) - IIf(cbx1_4.Value = "N/A", 1, 0)
OUTBX.Text = Format(a / b, "00%")

End Sub

或者如果您愿意:

Private Sub CommandButton1_Click()

OUTBX.Text = Format( _
    ( _
    IIf(cbx1_1.Value = "Yes", 1, 0) + _
    IIf(cbx1_2.Value = "Yes", 1, 0) + _
    IIf(cbx1_3.Value = "Yes", 1, 0) + _
    IIf(cbx1_4.Value = "Yes", 1, 0) _
    ) / _
    (4 - _
    IIf(cbx1_1.Value = "N/A", 1, 0) - _
    IIf(cbx1_2.Value = "N/A", 1, 0) - _
    IIf(cbx1_3.Value = "N/A", 1, 0) - _
    IIf(cbx1_4.Value = "N/A", 1, 0) _
    ), "00%")

End Sub