VBA-文本框值格式

时间:2019-08-21 07:01:39

标签: excel vba

我对文本框值的格式设置和检查条件有疑问

enter image description here

  1. 输入后的每个文本框将自动以百分比格式设置。

  2. 完成输入最后一个文本框后,它将检查总和是否等于1。

我可以在第一个工作。但是,当以某种方式检查三和时,我无法将值格式化为value / double。我从3个文本框中获得的值仍然在字符串中。我尝试转换但未成功。

请查看我的代码是否有问题

Private Sub Land_Prob1_AfterUpdate()
On Error Resume Next
If Form_Simulation.Land_Prob1 <= 100 Then
    Form_Simulation.Land_Prob1.Value = Format(Form_Simulation.Land_Prob1.Value / 100, "Percent")
ElseIf Form_Simulation.Land_Prob1 > 100 Or Form_Simulation.Land_Prob1 < 0 Then
    Form_Simulation.Land_Prob1 = "0.00%"
End If
End Sub

Private Sub Land_Prob2_AfterUpdate()
On Error Resume Next
If Form_Simulation.Land_Prob2 <= 100 Then
    Form_Simulation.Land_Prob2.Value = Format(Form_Simulation.Land_Prob2.Value / 100, "Percent")
ElseIf Form_Simulation.Land_Prob2 > 100 Or Form_Simulation.Land_Prob2 < 0 Then
    Form_Simulation.Land_Prob2 = "0.00%"
End If
End Sub

Private Sub Land_Prob3_AfterUpdate()
Dim x1, x2, x3
On Error Resume Next
If Form_Simulation.Land_Prob3 <= 100 Then
    Form_Simulation.Land_Prob3.Value = Format(Form_Simulation.Land_Prob3.Value / 100, "Percent")
ElseIf Form_Simulation.Land_Prob3 > 100 Or Form_Simulation.Land_Prob3 < 0 Then
    Form_Simulation.Land_Prob3 = "0.00%"
End If

'Check if total probability equal 100
If Form_Simulation.Land_Prob1.Value <> "" And Form_Simulation.Land_Prob2.Value <> "" Then
    x1 = Form_Simulation.Land_Prob1.Value
    x1 = CDbl(x1)
    x2 = Form_Simulation.Land_Prob2.Value
    x2 = CDbl(x2)
    x3 = Form_Simulation.Land_Prob3.Value
    x3 = CDbl(x3)
    If x1 + x2 + x3 <> 1 Then
        MsgBox "Total probability must be equal 100%. Please enter again"
        Form_Simulation.Land_Prob3 = ""
    End If
End If
End Sub

无论我如何尝试进行转换,该值仍然在字符串中,因此我无法将其汇总以进行条件检查

感谢您阅读

1 个答案:

答案 0 :(得分:0)

那么您正在尝试将它们转换为不带百分号的数字吗?

改为尝试以下方法:

x1 = CDbl(Replace(x1, "%", ""))