我正在尝试编写一些代码,要求您放入一定数量的代码。如果输入的号码不正确,则会弹出一个消息框,提示您重试或取消。如果再次单击try,它只会循环回到第一个问题,而cancel则使inputbox =“”,然后继续退出子菜单,并留下一个空单元格。问题是,到目前为止,将某处错误放入并单击取消的一次迭代会立即起作用,并且会留下一个空单元格。但是,如果我输入一个数字,例如33333,请再次单击“尝试”,然后输入22222(这仍然是错误的),然后单击“取消”,因为我想退出循环,它退出了循环,但留下了“ 22222”而不是将单元格留空。
Sub InputNum()
'input number
Dim lotData As String
'requests an input number to be put in
lotData = InputBox("Scan in Lot #")
'checks to ensure the number put in is 3 characters long
If Len(lotData) <> 3 Then
'error message
Result = MsgBox("Invalid Lot # Inputed. Must be 3 Characters. Try Again?", vbOKCancel)
'if cancel is clicked, input number is made blank and sub is exited
If Result = vbCancel Then
lotData = ""
Exit Sub
'if ok is clicked to try again, recurses to beginning of code again
Else
InputNum
End If
End If
'input number is put into current cell
ActiveCell.Value = lotData
End Sub
答案 0 :(得分:2)
类似的事情应该对您有用:
Sub InputNum()
Dim InputMsg As String 'shown message
Dim lotData As String 'input number
InputMsg = "Scan in Lot #"
Do
lotData = InputBox(InputMsg) 'ask user to enter lot number
If Len(lotData) = 0 Then Exit Sub 'pressed cancel, exit macro
If Len(lotData) = 3 Then Exit Do 'entered valid lot number, exit Do loop
InputMsg = "Invalid Lot # Inputed. Must be 3 Characters." & Chr(10) & "Scan in Lot #" 'Because invalid lot number was entered, update shown message to include the error
Loop
'input number is put into current cell
ActiveCell.Value = lotData
End Sub
答案 1 :(得分:2)
使用vbCancel
将lotData
设置为“”,但是在设置单元格值之前退出子菜单。在另一种情况下,您调用InputNum
,但是不退出子程序,因此它仍然运行ActiveCell.Value = lotData
行。
Sub InputNum()
'input number
Dim lotData As String
'requests an input number to be put in
lotData = InputBox("Scan in Lot #")
'checks to ensure the number put in is 3 characters long
If Len(lotData) <> 3 Then
'error message
Result = MsgBox("Invalid Lot # Inputed. Must be 3 Characters. Try Again?", vbOKCancel)
'if cancel is clicked, input number is made blank and sub is exited
If Result <> vbOK Then
ActiveCell.Value = ""
Else
InputNum
End If
Else
ActiveCell.Value = lotData
End If
End Sub