Excel - 最小必填字段数

时间:2015-06-29 09:54:33

标签: excel

我在Excel中创建一个表单,用户必须填写最少3/4的字段,但不是全部。如果他填充足够的字段,则输出将是所有字段的平均值。如果不是,则需要向他显示一些错误文本。

有人知道如何做到这一点?以下是示例:

示例1:

Field 1: Value 1
Field 2: Value 2
Field 3: Value 3
Field 4: Value 4
Result: Average of all 4 fields

示例2:

Field 1: Value 1
Field 2: Value 2
Field 3: Value 3
Field 4: Empty
Result: Average of 3 fields

示例3:

Field 1: Value 1
Field 2: Value 2
Field 3: Empty
Field 4: Empty
Result: Error Text

1 个答案:

答案 0 :(得分:0)

将此添加到UserForm的代码:

Private Sub CommandButton1_Click()

Dim cCont As Control
Dim Sum As Double, Count As Integer

Sum = 0
Count = 0

For Each cCont In Me.Controls

    If TypeName(cCont) = "TextBox" Then
        If IsNumeric(cCont.Text) Then
            Sum = Sum + cCont.Text
            Count = Count + 1
        End If
    End If

Next cCont

If Count > 2 Then
    MsgBox "Average of all " & Count & " fields: " & Sum / Count
Else
    MsgBox "Error Text"
End If

End Sub