【问题标题】:Verify if 2 textbox are empty when a user selects a combobox当用户选择组合框时验证 2 个文本框是否为空
【发布时间】:2021-02-04 23:15:23
【问题描述】:

我正在创建一个具有 2 个文本框和 1 个组合框的 VBA 表单。

我想创建以下条件。
当用户尝试更改组合框值而没有先将金额放入 2 文本框中时。
我想显示一条消息,例如“文本框需要有值”,不允许用户继续。

Sub TextBoxnull()
         
    If Len(TextBoxnull.txtTOPDtotalrem.Value) = 0 And Len(TextBoxnull.txtTOPDmedical.Value) > 0 Then
        MsgBox "Number must be entered to continue!"
    End If
    TextBoxnull.cboTOPDsuperannuationperc.Value = Format(TextBoxnull.cboTOPDsuperannuationperc.Value, "0%")
    Sheet1.Range("B10").Value = Format(TextBoxnull.cboTOPDsuperannuationperc.Value, "0%")
    With TextBoxnull
        .txtTOPtaxableremexclsuperannuation.Value = Format(Sheet1.Range("B13").Value, "$#,##0.00;-$#,##0.00")
        .txtTOPsuperannuationcontribution.Value = Format(Sheet1.Range("B14").Value, "$#,##0.00;-$#,##0.00")
        .txtTOPDtotalremnet.Value = Format(Sheet1.Range("B15").Value, "$#,##0.00;-$#,##0.00")
    End With
            
End Sub

【问题讨论】:

    标签: vba textbox


    【解决方案1】:

    请尝试此代码。这是一个在用户单击组合框时将运行的偶数过程。您必须将控件名称替换为您在表单中使用的名称。

    Private Sub ComboBox1_Enter()
    
        Dim i       As Integer
        Dim Tbx     As MSForms.TextBox
        
        Set Tbx = TextBox1
        For i = 1 To 2
            With Tbx
                If Len(Trim(.Value)) = 0 Then
                    .SetFocus
                    MsgBox "Please enter a value in the selected Text Box."
                    Exit For
                End If
            End With
            Set Tbx = TextBox2
        Next i
    End Sub
    

    如果您只是想测试代码,请创建一个包含 2 个名为 TextBox1 和 TextBox2 的文本框和一个名为 ComboBox1 的组合框的表单,如过程名称所示。

    【讨论】:

    • 您好@Variatus 感谢您的意见。如果用户选择组合框而不在 2 文本框中添加值,我将调用此过程
    • 你不调用这个过程。当用户单击 ComboBox 时,它会自动调用。如果两个文本框都被填满,则不会发生任何事情,但如果其中一个为空,它将被选中并显示一条消息。
    【解决方案2】:

    @variatus...

    我进行了更改,但它不起作用。我是 VBA 新手,我不确定我是否做错了什么......

    这是我调用的过程

    Private Sub cboTOPDsuperannuationperc_Change()
       Call m_TopDown.Taxableremexclsuperannuation1
    End Sub
    

    这是根据我的表单进行更改的代码。 Sub Taxableremexclsuperannuation1()

    Dim i       As Integer
    Dim Tbx     As MSForms.TextBox
    
    Set Tbx = frmTaxablepay.txtTOPDtotalrem
    For i = 1 To 2
        With Tbx
            If Len(Trim(.Value)) = 0 Then
                .SetFocus
                MsgBox "Please enter a value in the selected Text Box."
                Exit For
            End If
        End With
        Set Tbx = frmTaxablepay.txtTOPDmedical
    Next i
    

    结束子

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-09-30
      • 2019-05-04
      • 1970-01-01
      • 1970-01-01
      • 2012-05-17
      相关资源
      最近更新 更多