在vba中将msgbox与文本框进行比较时出错

我是VBA新手。 我在VBA中创build了一个将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 

您需要确保您从InpoutBoxTextBox中获得的所有值都是数字(在我的代码中转换为Long ,以保证安全):

 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 

处理之前需要inputvalidation

如下所示

 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()validation相关的userfominput

    你可能想要改变它来适应你的实际需要

  • 使用Application.InputBox()函数而不是VBA.InputBox()来利用其Type参数,并强制input一个数字

我认为你需要Long数字,不应该是这种情况,只需要用所需的数据types( DoubleInteger ,…)和CLng()与相应的types转换函数 ( CDbl()CInt()

你所要做的只是在获取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