Home > Back-end >  do loop not looping or generates loop without do error
do loop not looping or generates loop without do error

Time:10-22

hi one of my weekly files which we are trying to get into a macro/power query model to enable production by wider team is nearly finished but I'm having an issue with the loop that would provide the date portion of the file name. the file could be produced any day in the week or the first couple days the week after it relates to depending on when the source data is ready but must be prefixed with a date in yyyymmdd format of the last date it contains data on.

the easiest way to do this is to set this via an input box at the start of the macro running which can then be called upon later on when saving the component reports into their folders. my issue is the user could put anything into the input box (which i think needs to be formatted as string for other elements as i don't understand vba well enough to know how calling a number variable into my save as name would work). so I want to add a loop that says if it is 8 characters long and a numeric continue else re-enter date

Dim svdate As String
Sub inpt()
Do
svdate = InputBox("date")
If Len(svdate) = 8 And IsNumeric(svdate) Then
MsgBox svdate
Else
 MsgBox ("the value should be a number in format yyyymmdd please try inputting the date again")
End If
Loop Until True

as my vba is not great I have just been testing the above code in a separate sub hence the msgbox on the if true section which would be replaced with the rest of the subs that would be run once the date is entered correctly. i have defined the svdate variable as a module level item a it is called upon in many other stages within the wider macro which all work fine I just want the assurance that a user could only enter an appropriate date before combining the code.

as the code currently stands it'll ask me to input the date into the box and then show one of the 2 msgbox once but if false won't return to the add the input box stage as i would've guessed the loop until cline dictates. any help on this would be appreciated.

CodePudding user response:

Correct looping:

Dim svdate As String
Sub inpt()
dim isOK as boolean
Do
    svdate = InputBox("date")
    If Len(svdate) = 8 And IsNumeric(svdate) Then
       isOK = true
      MsgBox svdate
    Else
       isOK = false
       MsgBox ("the value should be a number in format yyyymmdd please try inputting the date again")
    End If
Loop Until isOK = true
End Sub

In your code the If-loop is inside the Do-loop - therefore the Do-loop does not 'know' about the result of the check.

With my code isOK is set by the If-loop and the do-loop can evaluate it.

  • Related