我有下面的代码来检查输入到两个输入框中的值,如果这两个值都是零,那么MsgBox应该显示“停止!”(稍后我会将其更改为退出潜艇,但我正在使用MsgBox进行测试)
通过测试,我看到了以下结果:
我还注意到,如果第二个字符串为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 & "%"发布于 2012-07-10 15:48:50
两件事
1)声明MinPer,MaxPer为Long或Double,而不是String,因为您正在存储计算的输出
2)不直接在计算中使用InputBox。将它们存储在变量中,然后如果输入有效,则在计算中使用它们。
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)发布于 2012-07-10 15:48:37
这是因为数字"10“在字符串(第二个字符)中有一个"0”,因此两者都计算为true。
试一试:
If (MinPer = "0") And (MaxPer = "0") Then
MsgBox "STOP!"
End If为了获得额外的控制,请保存用户输入(MinPer,MaxPer),然后在对它们执行否定的数学操作之前,将它们文本显示为有效性。
发布于 2012-07-10 15:48:54
InStr(MinPer,"0")只是检查字符串是否包含零字符。
您需要将字符串值转换为整数。使用IsNumeric和CInt函数来做到这一点。请参见此URL:
vba convert string to int if string is a number
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根据可以输入的数据,使用len()函数检查数据的长度是否为零也是个好主意。
https://stackoverflow.com/questions/11416940
复制相似问题