首页 > 解决方案 > 如何根据excel vba中的组合框值设置文本框的最小值?

问题描述

我已经尝试编写代码来设置文本框的限制,这意味着如果有人输入值 8,并且如果代码中的限制设置为 10,那么它应该给出 pl 的消息。增加输入的值,但加上它的限制值也会根据组合框中的值改变意味着我有 5 到 7 个数字的列表,如果有人选择特定限制,那么程序应该考虑相邻的单元格值分别如图所示

例如:如果有人选择数字 4456,那么在文本框中输入的最小值大于 50 与有人选择 5566 数字相同,那么如果有人输入低于该数字的值,那么在文本框中输入的最小值分别大于 150它应该显示 pl 的消息。增加值并显示 4456 的最小值要求为 50,例如。

PL。帮助解决这个问题欢迎任何积极的回应。PL。在附加文档中找到包含值的用户表单和工作表布局的图像。

Private Sub ComboBox1_Change()
Dim t As Long, LastRow As Long, ws As Worksheet
Set ws = Sheets("Sheet1")
LastRow = ws.Range("H" & Rows.Count).End(xlUp).Row

For t = 2 To LastRow
If Val(Me.ComboBox1.Value) = ws.Cells(t, "H").Value Then
Me.TextBox1 = ws.Cells(t, "I").Value

If Val(Me.ComboBox1.Value) = ws.Cells(t, "H").Value Then
If Val(Me.TextBox2.Value) < ws.Cells(t, "J").Value Then
    MsgBox ("Has to be greater than")
    
    End If
    End If

  End If

 Next t

 End Sub

[用户表单图像应将值的限制赋予第二个文本框][1] [限制值][2]

问候, Shubham Mehta

标签: excelvba

解决方案


我认为这里最好的形式是创建一个可以保存和返回所有这些数字组合的函数。像这样:

Function CurrentMinimumValue() As Long
'Manually type in all the pairs of selected numbers and the corresponding minimum values
    Select Case Me.ComboBox1.Value
        Case 10
            CurrentMinimumValue = 5
        Case 20
            CurrentMinimumValue = 15
        Case 4456
            CurrentMinimumValue = 50
        Case 5566
            CurrentMinimumValue = 150
    End Select
End Function

可以像这样使用:

Sub test()
    Me.Combobox1.Value = 4456
    MsgBox "The current minimum value allowed is " & CurrentMinimumValue()
    MsgBox "Is the entered value above the minimum? " & Me.TextBox2.Value > CurrentMinimumValue()
End Sub

你问的那行可以重写为:

If Val(Me.TextBox2.Value) < CurrentMinimumValue() Then
    MsgBox  "Has to be greater than " & CurrentMinimumValue()

推荐阅读