【问题标题】:How to limit inputbox response to specific range如何将输入框响应限制在特定范围内
【发布时间】:2018-01-23 22:10:17
【问题描述】:

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

【问题讨论】:

  • 您的总行是工作表中的最后一行吗?
  • 如果下面没有数据可以使用Worksheet.UsedRange.Rows
  • 为什么要让用户选择添加行的位置?您应该找到最后使用的行并加 1,然后将数据放在该行上。也许您应该扩展您的问题以更多地解释您实际想要做什么。通常,当您刚接触 VBA 时(就像我曾经一样!),您会发现自己正在尝试让某些东西发挥作用 - 但如果您以不同的方式解决问题,实际上会有更好的解决方案。首先是什么触发了子?

标签: vba excel inputbox


【解决方案1】:

lastrow的值交换22:

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

【讨论】:

    【解决方案2】:

    您可以尝试在将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 行上的条件以满足您的需要。希望这能让你继续前进。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-12-20
      • 1970-01-01
      • 2021-06-17
      • 1970-01-01
      • 1970-01-01
      • 2018-09-29
      相关资源
      最近更新 更多