vba - 仅允许数字作为 CommandButton1_Click() 的 Application.InputBox 的用户输入值

标签 vba excel

我正在努力解决一种令人烦恼的可能性,即用户可以插入小数/分数值,尽管只允许使用整数。 我尝试使用 KeyAscii (48-57) 来检查用户是否输入数字。但是,我无法让它工作,也无法使用其他一些功能。 用户不应该能够插入除数值(从 0 到 9 以及最多 99)以外的任何内容。这适用于我所附代码中的“rowNum”。 我可以控制其他一切,但我无法让我的 VBA 处理用户在按下 CommandButton_Click() 后插入的小数/分数值。 我现在已经尝试了很多小时来寻找解决方案,但没有成功。感谢所有帮助!

Private Sub CommandButton1_Click()
Dim rowNum As Variant
Dim x As Variant
On Error Resume Next

rowNum = Application.InputBox(Prompt:="Please enter the row from where you want to add new empty rows downwards:", _
                                    Title:="Need to add new empty rows?", Type:=1)

                If (VarType(rowNum) = vbBoolean) And (rowNum = False) Then
                MsgBox "You canceled the event!", vbExclamation, "No Input!"

                ElseIf rowNum = 0 Then
                MsgBox "Smallest allowed row number is 7!", vbExclamation, "Invalid Input!"

                ElseIf rowNum < 0 Then
                MsgBox "Negative values are not allowed!", vbExclamation, "Invalid Input!"

                ElseIf rowNum < 7 Then 
        MsgBox "Smallest allowed row number is 7!!", vbExclamation, "Invalid Input!"

        ElseIf rowNum > 99 Then 
        MsgBox "Highest allowed row number is 99!", vbExclamation, "Invalid Input!"

                              End If
                              If rowNum < 7 Or rowNum > 99 Then End



x = Application.InputBox(Prompt:="Please insert the amount of empty rows that you need:", _
                            Title:="Amount of new rows?", Type:=1)


                If (VarType(x) = vbBoolean) And (x = False) Then
                MsgBox "You canceled the event!", vbExclamation, "No Input!"

                ElseIf x = 0 Then
                MsgBox "Smallest amount of new rows is 2!", vbExclamation, "Invalid Input!"

                ElseIf x < 2 Then
                MsgBox "Smallest amount of new rows is 2!", vbExclamation, "Invalid Input!"

                ElseIf x > 10 Then
                MsgBox "Highest amount of new rows is 10!", vbExclamation, "Invalid Input!"

                              End If
                              If x < 2 Or x > 10 Then End

Rows(rowNum & ":" & rowNum + x - 1).EntireRow.Insert Shift:=xlDown

End Sub

最佳答案

添加另一个 elseif 子句

ElseIf x <> Int(x) Then
       MsgBox "Fraction number is not  allowed", vbExclamation, "Invalid Input!"


End if

可以解决问题

关于vba - 仅允许数字作为 CommandButton1_Click() 的 Application.InputBox 的用户输入值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52496110/

相关文章:

vba - WAV音频文件播放完毕后,VBA Powerpoint自动播放下一张幻灯片

excel - 返回范围值乘积的简单 VBA 函数

excel - 使用宏复制每 N 行

vba - 过滤和电子邮件 Excel 文件 (VBA)

vba - 删除子数据表

vba - 动态命名范围错误: 'Run-Time Error ' 1004 - Method 'Range' of object '_Worksheet' failed'

vba - 根据行的内容将代码更改为自动调整列宽

vba - Excel 2010 - 将单个 XSLM 导出到多个 CSV 文件

java - Apache POI 超链接无法在 Microsoft Excel 中打开

excel - 获取条件格式单元格的单元格颜色