简体   繁体   中英

VBA input box with loop and step

Hi I have the following code below which works but as you can see is very manual in terms of the loop until the input entry is correct. Basically I want the code to check that the number the user has entered equals 19 or any row number from 19 with a step /increment of 7 eg 26,33,40 etc. up to a maximum of 1002 so in effect my validation range is 19 to 1002, with step of 7 from 19. I have removed some of the myvalue code for the purposes of this post to reduce size. Any help would be appreciated, thanks.

sub InsertRows()

Dim lastRow As Long
Dim Row1 As Long
Dim Row2 As Long
Dim myvalue As Variant
Dim i As Long
Dim CancelTest As Variant
Dim Row As Range
Dim myPassword As String
 myPassword = "Password"

Application.ScreenUpdating = False

lastRow = 0
Do
myvalue = InputBox("Insert Rows Starting From Input Number:" & Chr(10) & _
                    "e.g. 19, 26, 33 (Multiples of 7)")
If StrPtr(myvalue) = 0 Then Exit Sub

If Not IsNumeric(myvalue) Then MsgBox "Numeric Values Only" & Chr(10) & _
                                   "Starting From Row 19 In Multiples Of 7"

Loop Until Val(myvalue) = 19 Or myvalue = 26 Or myvalue = 33 Or myvalue = 40 Or myvalue = 47 Or myvalue = 54 Or myvalue = 61 Or myvalue = 68 Or myvalue = 75 Or myvalue = 82 Or myvalue = 89 Or myvalue = 96 Or myvalue = 103 

If MsgBox("Are you sure?", vbYesNo) = vbNo Then Exit Sub

With Sheet1
    .Select
    .Unprotect Password:=myPassword

   ActiveSheet.Outline.ShowLevels RowLevels:=2

    lastRow = Cells(Rows.Count, "B").End(xlUp).Row
    Row1 = lastRow - 6
    Row2 = lastRow
    Rows(Row1 & ":" & Row2).Select
    Selection.Copy
End With

With Sheet1
    .Select
    Range("a" & myvalue).Select
    Selection.Insert Shift:=xlDown
    On Error GoTo 0
    Application.CutCopyMode = False
    lastRow = 0
    .Range("c11").Select
    .Protect Password:=myPassword, AllowFiltering:=True, AllowFormattingCells:=True, DrawingObjects:=False, Contents:=True, UserInterfaceOnly:=True, AllowFormattingRows:=True, AllowFormattingColumns:=True

End With

Application.ScreenUpdating = True

End Sub

使用Mod运算子

=Loop Until Val((myvalue - 19) Mod 7)) = 0

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM