意外的string结果

我有以下代码来检查input到两个input框中的值,如果两个值均为零,则MsgBox应显示“Stop!”。 (我会改变这个稍后退出sub,但我正在使用MsgBox进行testing)

从testing我看到了这些结果:

  • 两个string中的零都会生成预期的消息框。

  • 第一个string中的非零值,第二个string中的任何非零值都不会执行任何操作(如预期的那样)。

  • 在第一个string后面跟着第二个string值等于或大于10的零产生消息框(意外的)。

我也注意到,如果第二个string是6-9它显示为x.00000000000001% 。 我认为这是一个浮点问题,可能是相关的? 此行为发生没有IF... InStr函数也。

 Option Explicit Sub Models() Dim MinPer As String, MaxPer As String, Frmula As String Dim Data As Worksheet, Results As Worksheet Set Data = Sheets("Data") Set Results = Sheets("Results") Application.ScreenUpdating = False MinPer = 1 - InputBox("Enter Minimum Threshold Percentage, do not include the % symbol", _ "Minimum?") / 100 MaxPer = 1 + InputBox("Enter Maximum Threshold Percentage, do not include the % symbol", _ "Maximum?") / 100 If (InStr(MinPer, "0") = 0) And (InStr(MaxPer, "0") = 0) Then MsgBox "STOP!" End If ' Remainder of code... 

这是迄今为止在VBA中遇到的最有趣的问题,欢迎大家进行讨论。

编辑:我使用这个代码在屏幕上显示最终用户看到的参数。 因此,我怎么注意到.00000000001%问题:

  .Range("D2").Value = "Min is " & 100 - MinPer * 100 & "%" .Range("D3").Value = "Max is " & MaxPer * 100 - 100 & "%" 

两件事情

1)在存储计算输出时,将MinPerMaxPer声明为LongDouble或不是String

2)不要在计算中直接使用InputBox 。 将它们存储在variables中,然后如果input有效,则在计算中使用它们

 Dim MinPer As Double, MaxPer As Double, Frmula As String Dim Data As Worksheet, Results As Worksheet Dim n1 As Long, n2 As Long Set Data = Sheets("Data") Set Results = Sheets("Results") Application.ScreenUpdating = False On Error Resume Next n1 = Application.InputBox(Prompt:="Enter Minimum Threshold Percentage, do not include the % symbol", _ Title:="Minimum?", Type:=1) On Error GoTo 0 If n1 = False Then MsgBox "User cancelled" Exit Sub End If On Error Resume Next n2 = Application.InputBox(Prompt:="Enter Maximum Threshold Percentage, do not include the % symbol", _ Title:="Maximum?", Type:=1) On Error GoTo 0 If n2 = False Then MsgBox "User cancelled" Exit Sub End If If n1 = 0 And n2 = 0 Then MsgBox "STOP!" End If MinPer = 1 - (Val(n1) / 100) MaxPer = 1 + (Val(n2) / 100) 

这是因为数字“10”在string(第二个字符)中有一个“0”,所以都评估为真。

试试这个:

 If (MinPer = "0") And (MaxPer = "0") Then MsgBox "STOP!" End If 

对于额外的控制,保存用户input(MinPer,MaxPer),然后在对它们执行math运算之前对它们进行文本validation。

InStr(MinPer,“0”)只是检查string是否包含零字符。

您需要将string值转换为整数。 使用IsNumeric和CInt函数来做到这一点。 看到这个url:

vba将string转换为int如果string是一个数字

 Dim minPerINT as Integer Dim maxPerINT as Integer If IsNumeric(minPer) Then minPerINT = CInt(minPer) Else minPerINT = 0 End If If IsNumeric(maxPer) Then maxPerINT = CInt(maxPer) Else maxPerINT = 0 End If If minPerINT = 0 and maxPerINT=0 Then MsgBox "STOP!" End If 

取决于可以input什么数据使用len()函数检查数据长度是否为零也是一个好主意。