VBA用户表单中的多个算术运算

时间:2016-07-05 06:44:43

标签: vba

我正在努力将多个文本框(A,B,C)的值汇总到一个文本框(D)中,并获得文本框的百分比贡献(A / D,B / D,C / D)并将百分比值放入其他文本框(E,F,G)。

我使用以下代码

成功地总结了这些值
If A.Value = "" Then Exit Sub

If B.Value = "" Then Exit Sub

If C.Value = "" Then Exit Sub

D.Value = CDbl(A.Value) + CDbl(B.Value) + CDbl(C.Value)

我很难计算A,B,C在E,F,G盒子中的百分比。

如果有人能帮我编写这些东西,真的很感激。

谢谢

1 个答案:

答案 0 :(得分:1)

首先,我认为你应该使用texbox的.Text属性,如果你想为它们设置一个新值供用户查看。

.Text.Value属性之间存在细微差别,您可以查看我提供的链接。总而言之,.Text显示信息,可能与文本框所持有的.Value不同。

根据您所写的内容,我了解您是否希望根据输入数字显示用户的信息。

因此,我认为以下代码可以解决这个问题:

' Also, to prevent the updating of every items of the Userfrom 
' and then calculate the percentages, I would suggest using variables
Dim aVal As Single, bVal As Single, cVal As Single, tempVal As Single

If A.Text = "" Then Exit Sub
aVal = CDbl(A.Text)

If B.Text = "" Then Exit Sub
bVal = CDbl(B.Text)

If C.Text = "" Then Exit Sub
cVal = CDbl(C.Text)

tempVal = aVal + bVal + cVal

' Displaying the values in the different textboxes and rounding the percentages
D.Text = tempVal
E.Text = round(aVal / tempVal * 100, 2)
F.Text = round(bVal / tempVal * 100, 2)
G.Text = round(cVal / tempVal * 100, 2)

问候。