【问题标题】:How to calculate multiplication and percentage in user-form?如何以用户形式计算乘法和百分比?
【发布时间】:2014-11-29 12:46:15
【问题描述】:

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

Textbox5 = Textbox1 * Textbox2 (with discount) Textbox3


我有第一个的代码:

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

【问题讨论】:

  • 您能否澄清一下,您在输入数量之前是否为 TextBox2 和 3 设置了值?为什么必须发生 afterUpdate 事件?如果您输入三个顶部框,然后单击计算。另外,您是否在实际的 Textbox3 中添加了“%”?
  • 我在 TextBoxes 中输入数据并按计算,“afterUpdate”是我的错,应该是“Private Sub TextBox3_BeforeUpdate(ByVal Cancel As MSForms.ReturnBoolean)”
  • 但是如果你看到我在textbox2价格和折扣和textbox3输入时也有问题?!我没有得到你需要的东西。比如一个1000的30%是700但是我得到了300,要怎么反转呢?
  • 1000的30%其实就是300。折扣是你拿走多少,价格是原价——折扣。
  • 好的,我的英语有点差,但是你能帮我写代码而不是数学吗?

标签: excel vba


【解决方案1】:

这有点过分了变量,但它已经过测试并且有效。从文本框中声明变量,然后在公式中使用变量名称可以更轻松地查看正在完成的实际数学运算,而不是专注于数据转换。

正如上面评论中所述,我不会在文本框中包含 %,但 Replace 函数确实可以解决这个问题。

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

【讨论】:

  • “CLng 转换”有问题,总是为 0 而不是,例如 0.3。 (占 30%)理论上很好,应该可以,但是……我不知道怎么回事!
  • 我应该使用 Single Variable 类型,而不是 Long。
  • 你太棒了!仅当可以在正确的位置添加逗号时,Like this.
  • 我很高兴你能通过它。确保您在 discPct 中包含“/100”。
  • 是的,我包括了“/100”,但没关系。我还有一个问题,为什么你 Dim qty As Long 而所有其他的都是单身?!
猜你喜欢
  • 1970-01-01
  • 2023-03-09
  • 2021-04-12
  • 1970-01-01
  • 2017-01-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多