View Single Post
 
Old 05-29-2018, 02:47 AM
slaycock slaycock is offline Windows 7 64bit Office 2016
Expert
 
Join Date: Sep 2013
Posts: 255
slaycock is on a distinguished road
Default

Well done. I'm impressed with your ability to extend the userform based on previous instructions.

Its very easy to update the code to validate the page range you want.

The first trick is to use the Trim and Replace functions to get rid of any commas and hyphens and multiple spaces.

You can then split the list of page numbers separated by spaces using the split function to give an array of page numbers

You can then test each page number in turn for it being numeric.

This is the updated code for the form_validates_ok function If it were for my personal use then there would be some further abstraction as the validation is quite repetitive.

Code:
Private Function form_validates_ok() As Boolean

Dim txt_pages                               As String
Dim pages()                                  As String
Dim a_page_number                      As Variant  ' must be a variant for loop control

    If Not IsNumeric(Trim(Me.txtCopies)) Then
        MsgBox "The number of copies should be a number", vbOKOnly
        Me.txtCopies.SetFocus
        Me.txtCopies.SelLength = Len(Me.txtCopies)
        form_validates_ok = False
        Exit Function
    End If
    
    If Not IsNumeric(Trim(Me.txtStartNumber)) Then
        MsgBox "The start number should be a number", vbOKOnly
        Me.txtStartNumber.SetFocus
        Me.txtStartNumber.SelLength = Len(Me.txtStartNumber)
        form_validates_ok = False
        Exit Function
    End If
    
    ' convert the txtPages string into an array of page numbers in array pages
    txt_pages = Trim(Me.txtPages)
    txt_pages = replace(txt_pages, ",", " ")
    txt_pages = replace(txt_pages, "-", " ")
    Do While InStr(txt_pages, "  ") > 0 ' checking for the presence of two spaves adjacent to each other
        txt_pages = replace(txt_pages, "  ", " ")
    Loop
    pages = split(txt_pages, " ") ' Note the absence of () when assigning to an array
    
    For Each a_page_number In pages
        If Not IsNumeric(a_page_number) Then
            MsgBox "The pages required should be a number", vbOKOnly
            Me.txtPages.SetFocus
            Me.txtPages.SelLength = Len(Me.txtPages)
            form_validates_ok = False
            Exit Function
        End If
    Next
    
    form_validates_ok = True
    
End Function
You will also need to amend the printout statement to use the page ranges in .txtxPages

Code:
ActiveDocument.PrintOut copies:=1, pages:=my_form.txtPages
Reply With Quote