如何计算用户表单中的乘法和百分比?

时间:2014-11-26 20:24:51

标签: excel-vba vba excel

我需要帮助从图像中获取此表单的代码(数量是金额!)。当我按"计算"在折扣(Textbox3)中获得一件价格(Textbox2)的文本框4的结果,同时导致金额的Textbox4(Textbox1)乘以价格(Textbox2)和折扣(Textbox3)。 像这样: Textbox4 = Textbox3 (discount of) Textbox2

Textbox5 = Textbox1 * Textbox2 (with discount) Textbox3


enter image description here

我有第一个代码:

Private Sub TextBox1_AfterUpdate()
    With TextBox3
        .Text = format(Val(Replace(.Text, "%", vbNullString)) / 100, "#.0# %")
    End With
End Sub

Private Sub CommandButton1_Click()
    TextBox4.Text = Val(Replace(TextBox3.Text, "%", vbNullString)) / 100 * Val(TextBox2.Text)
End Sub

1 个答案:

答案 0 :(得分:0)

这对变量有点过分,但它已经过测试和运作。从文本框中声明变量,然后使用公式中的变量名称可以更容易地看到实际的数学运算,而不是关注数据转换。

同样如上面的评论中所述,我不在文本框中包含%,但替换功能确实考虑了它。

Private Sub CommandButton1_Click()

Dim qty As Long         'Quantity
Dim discPct As Single    'Discount Percentage
Dim unitPrice As Single    'Single Normal Price
Dim discPrice As Single    'Single Price After Discount
Dim total As Single    'Total Qty * Discounted Single Price

qty = CSng(TextBox1.Text)
unitPrice = CSng(TextBox2.Text)
discPct = CSng(Replace(TextBox3.Text, "%", "")) / 100

discPrice = unitPrice - (discPct * unitPrice)
TextBox4.Value = discPrice

total = qty * discPrice
TextBox5.Value = total

End Sub