VBA如果声明问题
我正在使用一个带有四个文本框的用户表单,用户input的数字值必须达到(在四个input端)总共为1。
然后,我将这些值与单元格值一起使用来执行计算。 为了试图阻止用户input小于或大于1的累积值,我使用下面的If语句,单击用户表单的“确定”button后执行。
但是,Then语句(显示MsgBox和退出子),即使值为1。无论值是什么,If语句被发现是真实的。 有任何想法吗?
Private Sub OKButton_Click() If DirectorBox.Value + SnrBox.Value + MngrBox.Value + ResearcherBox.Value <> 1 Then MsgBox "Values must amount to a total of 1" Exit Sub End If Sheets("Menu").Range("G13").Value = (Range("G9").Value * DirectorBox.Value) _ + (Range("G10").Value * SnrBox.Value) + (Range("G11").Value * MngrBox.Value) _ + (Range("G12").Value * ResearcherBox.Value) Unload UserForm1 End Sub
文本框保存文本,而不仅仅是数字,所以Value
属性的数据types是一个string。
你在If行上的testing正在做一个string连接而不是一个数字加法,所以这个值不能等于一个数字1。
您需要将文本框中的数字的文本表示转换为实际的数字。 假设input的值是分数,这应该工作:
Private Sub OKButton_Click() dim checkVal As Double If IsNumeric(DirectorBox.Value) Then checkVal = CDbl(DirectorBox.Value) If IsNumeric(SnrBox.Value) Then checkVal = checkVal + CDbl(SnrBox.Value) If IsNumeric(MngrBox.Value) Then checkVal = checkVal + CDbl(MngrBox.Value) If IsNumeric(ResearcherBox.Value) Then checkVal = checkVal + CDbl(ResearcherBox.Value) If checkVal <> 1# Then MsgBox "Values must amount to a total of 1" Exit Sub End If Sheets("Menu").Range("G13").Value = (Range("G9").Value * DirectorBox.Value) _ + (Range("G10").Value * SnrBox.Value) + (Range("G11").Value * MngrBox.Value) _ + (Range("G12").Value * ResearcherBox.Value) Unload UserForm1 End Sub
注意: “1#”确保文字“1”也是Double
types,与checkVal
相同。 否则解释器会认为它是一个Integer
。 vba:什么是97.45 * 1#=?