Excel要求:用户通过输入对话框输入数字。在当前选择的指定(硬编码)列中包含该数字的行将被删除。
关于输入验证,我没有提出或找到涵盖所有这些问题的解决方案:
我尝试过各种代码,但每个代码中至少有一个问题。以下代码是从我原来的帖子修改的。到目前为止,这是我最好的解决方案。唯一的问题是取消导致"没有输入值。" 感谢。
Sub DeleteRows()
On Error GoTo InvalidInput
Dim InputRng As Range
Dim DeleteRng As Range
Dim DeleteNum As Double
Dim DeleteV As Variant
Dim CountDelete As Long
Dim CountAreas As Long
Dim Str As String
Set InputRng = Application.Selection.Rows
DeleteV = Application.InputBox("Match Value", "Delete Rows")
'TODO Ultimate solution: Check for cancel so as not to result in "No value entered".
'NOTE: If DeleteV = Empty is true upon cancel
'NOTE this unwantingly matches zero: If DeleteV = False Then Exit Sub
'Check something was entered
If DeleteV = Empty Then
MsgBox ("No value entered.")
Exit Sub
End If
DeleteNum = CDbl(DeleteV)
'Accumulate what is to be deleted
For Each r In InputRng.Rows
'Only if cell is a number
If Not IsEmpty(r.Cells(3)) Then
If IsNumeric(r.Cells(3).Value) Then
If r.Cells(3).Value = DeleteNum Then
If DeleteRng Is Nothing Then
Set DeleteRng = r
Else
Set DeleteRng = Application.Union(DeleteRng, r)
End If
End If
End If
End If
Next
If DeleteRng Is Nothing Then
MsgBox ("Nothing to delete.")
Exit Sub
End If
CountDelete = 0
'The range may contain separated areas,
'so loop through each area to accumulate the total count
For Each a In DeleteRng.Areas
CountDelete = CountDelete + a.Rows.Count
Next a
If CountDelete > 1 Then
Str = " rows."
Else
Str = " row."
End If
'Confirm delete
If MsgBox("Confirm delete " & CountDelete & Str, vbYesNo) = vbYes Then
DeleteRng.EntireRow.Delete
End If
Exit Sub
InvalidInput:
MsgBox ("Invalid input.")
End Sub
答案 0 :(得分:0)
尝试使用类型1
<强>语法强>:
expression.InputBox(提示,标题,默认,左,顶部,帮助文件,帮助文本ID,类型)
<强>类型强>:
下表列出了可以在Type参数中传递的值。可以是一个值或一个值的总和。例如,对于可以接受文本和数字的输入框,请将“类型”设置为1 + 2。
Value Meaning
0 A formula
1 A number
2 Text (a string)
4 A logical value (True or False)
8 A cell reference, as a Range object
16 An error value, such as #N/A
64 An array of values
DeleteV = Application.InputBox("Match Value", "Delete Rows", Type:=1)
Sub Sample()
'~~> Only valid numbers are allowed including 0
'~~> Empty input will not to be accepted.
DeleteV = Application.InputBox("Match Value", "Delete Rows", Type:=1)
'~~> If user presses Cancel
If DeleteV = "False" Then Exit Sub
'~~> If user enters a number else it won't execute this
If DeleteV >= 0 Then
'
'~~> Rest of your code
'
End If
End Sub
您需要处理的积分
If-EndIf
If-EndIf