我是VBA的新手。我在VBA中创建了一个程序,它将msgbox值与文本框值进行比较,但结果不正确。我复制了下面的代码。我做错了什么?请帮帮我。
Private Sub CommandButton1_Click()
Dim num As String
num = Application.InputBox("enter num")
If TextBox1.Value * num > TextBox2.Value Then
MsgBox "textbox1 is higher"
Else
MsgBox "textbox2 is higher"
End If
End Sub
答案 0 :(得分:1)
在处理之前需要输入验证
如下
Option Explicit
Private Sub CommandButton1_Click()
Dim num As Long, tb1Val As Long, tb2Val As Long
Const DEFNUM As Long = 1 '<--| define a default value for 'num'
If Not ValidateInput(tb1Val, tb2Val) Then Exit Sub '<--| exit if textboxes have improper input
num = Application.InputBox("enter num", , DEFNUM, Type:=1) '<-_| 'Type:=1' forces a number input
With Me
If tb1Val * num > tb2Val.Value Then
MsgBox "textbox1 is higher"
Else
MsgBox "textbox2 is higher"
End If
End With
End Sub
Function ValidateInput(tb1Val As Long, tb2Val As Long) As Boolean
With Me
If IsNumber(.TextBox1) And IsNumber(.TextBox2) Then
tb1Val = CLng(.TextBox1.Value)
tb2Val = CLng(.TextBox2.Value)
ValidateInput = True
Else
MsgBox "Improper textbox input, try again", vbCritical
End If
End With
End Function
你可以看到:
要求Function ValidateInput()
验证相关的用户输入
您可能希望根据实际需要进行更改
使用Application.InputBox()
函数代替VBA.InputBox()
来利用其Type
参数并强制输入数字
我认为您需要Long
个数字,如果不是这样,只需更改所有Long
次出现的所需数据类型(Double
,Integer
,... )和CLng()
以及相应的Type conversion function(CDbl()
,CInt()
,......
答案 1 :(得分:0)
您需要确保从InpoutBox
和TextBox
获得的所有值都是数字(在我的代码中转换为长,只是为了安全起见):
Private Sub CommandButton1_Click()
Dim num As Long
' convert the number received from the InputBox to a number (type Long)
num = CLng(Application.InputBox("enter num"))
If CLng(TextBox1.Value) * num > CLng(TextBox2.Value) Then
MsgBox "textbox1 is higher"
Else
MsgBox "textbox2 is higher"
End If
End Sub
答案 2 :(得分:0)
你需要做的就是在获取TextBox值时使用Val()函数。这意味着您必须使用Val(TextBox1.Value)
而不是TextBox1.Value
Private Sub CommandButton1_Click()
Dim num As String
num = Application.InputBox("enter num")
If Val(TextBox1.Value) * num > Val(TextBox2.Value) Then
MsgBox "textbox1 is higher"
Else
MsgBox "textbox2 is higher"
End If
End Sub