Average of TextBoxes that are not blank

时间:2015-10-30 23:50:43

标签: excel vba excel-vba

I need the average of five TextBoxes but there is a chance that some of them may be empty. If so, it should only consider the filled TextBoxes. I have some code to find the sum of those but couldn't succeed in finding the average: Tot = Tot + CDbl(TextBox117.Text) Tot = Tot + CDbl(TextBox118.Text) Tot = Tot + CDbl(TextBox119.Text) Tot = Tot + CDbl(TextBox120.Text) Tot = Tot + CDbl(TextBox121.Text) TextBox70.Text = Tot I even tried counting the number of boxes but still couldn't get the result.

2 个答案:

答案 0 :(得分:1)

Dim arr, i As Long, n As Long, t As Double, v arr = Array(TextBox117, TextBox118, TextBox119, TextBox120, TextBox121) n = 0 t = 0 For i = lbound(arr) to ubound(arr) v = Trim(arr(i).Text) If Len(v) > 0 Then t = t + CDbl(v) n = n + 1 End If Next i TextBox70.Text = t TextBox71.Text = t/n

答案 1 :(得分:0)

Dim divNum As Integer Dim Tot As Double Dim numsAdd(4) As String numsAdd(0) = TextBox1.Text numsAdd(1) = TextBox2.Text numsAdd(2) = TextBox3.Text numsAdd(3) = TextBox4.Text numsAdd(4) = TextBox5.Text divNum = 0 For i = 0 To UBound(numsAdd) If numsAdd(i) <> "" Then Tot = Tot + CDbl(numsAdd(i)) divNum = divNum + 1 End If Next i TextBox6.Text = Tot / divNum