Я новичок в циклах VBA. То, что я пытаюсь сделать, - это процедура цикла do и поля ввода, которая запрашивает код продукта до тех пор, пока не будет введен действительный код. Код должен начинаться с буквы P и сопровождаться четырьмя цифрами. При вводе недопустимого кода должно отображаться сообщение, сообщающее пользователю, почему код недействителен.
У меня закодирована следующая процедура. Это работает, например, когда пользователь вводит p9887.
Однако, если пользователь вводит o899876 или p877789, появляется сообщение "Код продукта должен состоять из пяти символов", после чего пользователю приходится вводить снова. При этой второй попытке, если пользователь вводит p9876, хотя он соответствует всем критериям, в результате моей процедуры появляется сообщение: «Последние четыре символа должны быть цифрами», и оно застревает в том цикле, где пользователь должен ввести свои введите еще раз, и появится то же сообщение.
Любое понимание того, что я делаю неправильно, очень ценится!
Option Explicit
Public Sub ProductCode()
Dim strInput As String
Dim intFrstLetter As Integer
Dim intLastFour As String
Dim strFrstLetter As String
Dim test As String
Dim blDone As Boolean
strInput = InputBox("Please enter product code")
intFrstLetter = InStr(1, strInput, "p")
intLastFour = Right(strInput, 4)
strFrstLetter = Left(strInput, 1)
Do
If strFrstLetter = "p" Then
If Len(strInput) <> 5 Then
MsgBox "Product code should have five characters."
strInput = InputBox("Please enter product code")
Else
If IsNumeric(intLastFour) Then
MsgBox "Thank You"
blDone = True
Exit Do
Else
MsgBox "The last four characters should be digits"
strInput = InputBox("Please enter product code")
If strFrstLetter <> "p" Then
MsgBox "Product code should start with the letter P"
strInput = InputBox("Please enter product code")
End If
End If
End If
End If
Loop Until blDone = True
End Sub
************************ Вот еще один тип кода, который чище, но все еще делает ту же проблему.
Public Sub ProductCode()
Dim strInput As String
Dim intFrstLetter As Integer
Dim intLastFour As String
Dim strFrstLetter As String
Dim blDone As Boolean
strInput = InputBox("Please enter product code")
intFrstLetter = InStr(1, strInput, "p")
intLastFour = Right(strInput, 4)
strFrstLetter = Left(strInput, 1)
Do
If strFrstLetter = "p" Then
If Len(strInput) = 5 Then
If IsNumeric(intLastFour) = True Then
MsgBox "Thank You"
Exit Do
Else
MsgBox "The last four characters should be digits"
strInput = InputBox("Please enter product code")
End If
Else
MsgBox "Product code should have five characters"
strInput = InputBox("Please enter product code")
End If
Else
MsgBox "Product code should start with the letter P"
strInput = InputBox("Please enter product code")
End If
Loop