如何将输入框响应限制为特定范围

时间:2018-01-23 22:10:17

标签: vba excel-vba inputbox excel

VBA世界的新手。另一个线程有助于创建InputBox并设置特定范围,但不是我需要的。

我让用户将行号输入InputBox,他们想要添加一行,但我想限制他们从第12行(我的数据开始的地方)输入的值到总行上方的行。如何引用总行,因为它会随着行的添加而改变?以及如何将默认行设置在总行上方? (目前我的总排是第22行)

Dim varUserInput As Variant
varUserInput = InputBox("Please enter the row number where you'd like to add a row:", _
"What Row?")
If varUserInput = "" Then Exit Sub
If Not IsNumeric(varUserInput) Or varUserInput < 12 Or 22 < varUserInput 
Then 'If value out of specified range
    varUserInput = 22 'Default value
    MsgBox "You Entered a wrong value, using default", vbOKOnly
End If

2 个答案:

答案 0 :(得分:0)

将22与lastrow的值交换:

Sub Test()

Dim varUserInput As Variant, sht As Worksheet, lastrow As Long

Set sht = ThisWorkbook.Worksheets("Sheet1") 'specify sheet here
lastrow = sht.Cells(sht.Rows.Count, "A").End(xlUp).Row 'referencing column A

varUserInput = InputBox("Please enter the row number where you'd like to add a row:", _
"What Row?")

If varUserInput = "" Then Exit Sub

If Not IsNumeric(varUserInput) Or varUserInput < 12 Or lastrow < varUserInput Then 'If value out of specified range

    varUserInput = lastrow 'Default value
    MsgBox "You Entered a wrong value, using default", vbOKOnly

End If

End Sub

答案 1 :(得分:0)

您可以尝试设置默认参数,同时将InputBox调用到最后一行(或其他)。
然后更改提示,指导用户输入的数字是什么接受。
如下所示:

Sub marine()
    Dim varUserInput As Variant
    Dim lr As Long, myprompt As String

    With Sheet1 '/* change to your actual sheet */
        lr = .Range("A" & .Rows.Count).End(xlUp).Row '/* checks column A, change to suit*/
        myprompt = "Please enter the row number where you'd like to add a row:"
        Do
            '/* enter your last row as default */
            varUserInput = InputBox(myprompt, "What Row?", lr)
            myprompt = "You entered an invalid row number." & vbNewLine & _
                       "Please enter row number between 12 and " & lr
            If varUserInput = "" Then Exit Do '/* if user cancels */
            If Not IsNumeric(varUserInput) Then
                myprompt = "Invalid entry, numeric value expected." & vbNewLine & _
                           "Please enter numbers between 12 and " & lr & "."
            End If
        Loop Until varUserInput <= lr And varUserInput >= 12
    End With
End Sub

因为你说你被允许输入大于总行数的值,所以我不能完全得到你想做的事情?那么这将限制用户在数据的边界内添加行(第12行和最后一行)。如果这不是您所需要的,请调整Loop Until行的条件以满足您的需求。希望这能帮到你。