In Microsoft Word’s print dialog, there’s a textbox called Pages. In it, you can specify which pages you want to print by separating individual pages and page ranges by a comma.
I have a small app wherein I enter a starting serial number and an ending serial number. The output is a string of serial numbers in between. I wanted to be able to deal with nonconsecutive serial numbers a little more elegantly, so I set out to replicate Word’s Pages textbox.
‘returns a 1-dim array of all pages to print
Dim vaCommaSplit As Variant
Dim vaHyphSplit As Variant
Dim i As Long, j As Long
Dim lLower As Long, lUpper As Long
Dim aResult() As Long
Dim lResCnt As Long
vaCommaSplit = Split(sInput, “,”)
For i = 0 To UBound(vaCommaSplit)
‘if there is no hyphen, vaCommaSplit(i) is returned
vaHyphSplit = Split(vaCommaSplit(i), “-“)
‘no hyphen means lLower = lUpper
lLower = Val(vaHyphSplit(0))
lUpper = Val(vaHyphSplit(UBound(vaHyphSplit)))
For j = lLower To lUpper
lResCnt = lResCnt + 1
ReDim Preserve aResult(1 To lResCnt)
aResult(lResCnt) = j
PagesToPrint = aResult
Dim sInput As String
Dim i As Long
Dim vaPages As Variant
sInput = “1,3-5,10”
vaPages = PagesToPrint(sInput)
For i = LBound(vaPages) To UBound(vaPages)
The Split function returns a zero-based array of elements after it splits a string by the delimiter. If the delimiter doesn’t exist, Split return a single element array with the original string. Because of this, I don’t have to test if there’s a hyphen (meaning a range) or not (just a single number). If it’s just a single number,
UBound(vaHyphSplit) will be zero and lUpper and lLower will be the same. That means the inner loop will execute exactly once and put lLower in the result array.
Error checking needed: I put a Val() in there to help with non-numerical stuff, but that needs to be beefed up. I also need to make sure the number before the hyphen is less than the one after. Sounds like version 2 “features”.