【问题标题】:Error while comparing msgbox with textbox in vba将 msgbox 与 vba 中的文本框进行比较时出错
【发布时间】:2016-09-04 10:28:35
【问题描述】:

我是 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

【问题讨论】:

  • 根据您的代码,您正在尝试比较 2 个TextBoxs 和一个InputBox,对吗?如果是这种情况,请参阅下面的答案

标签: vba excel


【解决方案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()验证相关的userfom输入

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

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

我假设您需要 Long 数字,如果不是这种情况,只需将所有出现的 Long 更改为所需的数据类型(DoubleInteger,...),并将 CLng() 更改为相应的 @ 987654322@ (CDbl(), CInt(), ...

【讨论】:

  • ++ 解释得很好:)
【解决方案2】:

您需要确保从 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

【讨论】:

    【解决方案3】:

    您只需在获取 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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-10-11
      • 2016-08-06
      • 1970-01-01
      • 1970-01-01
      • 2016-04-07
      • 1970-01-01
      • 2021-08-14
      • 2021-11-01
      相关资源
      最近更新 更多