I agree with you Bigal , why not use blocks or layouts. But maybe user has some historical baggage I dunno...
But if OP has to use polylines I would recommend putting them in a special layer so selecting them would be easier by including layer name in selection filter.
anyways , another code that also sorts the polylines (untested of course since we have no sample to test it on)
(defun c:t4 ( / a sp i ss to p)
(setq a (vla-get-activedocument (vlax-get-acad-object)) sp (vla-get-block (vla-get-activelayout a)) i 0)
(prompt "\nSelect polylines to number :")
(if (setq ss (ssget ":L" '((0 . "LWPOLYLINE"))))
(foreach p (vl-sort (mapcar '(lambda (x) (GetBcent x)) (setq ss (vl-remove-if 'listp (mapcar 'cadr (ssnamex ss)))))
'(lambda (a b)(if (equal (cadr a) (cadr b) 1e-8) (< (car a) (car b)) (> (cadr a) (cadr b)))))
(setq to (vla-AddText sp (itoa (setq i (1+ i))) (vlax-3d-point p) (/ (getvar 'viewsize) 50)))
(vla-put-Alignment to acAlignmentRight)(vla-put-textalignmentpoint to (vlax-3d-point p))(vla-put-Alignment to acAlignmentMiddle)
)
)
(vla-Regen a acActiveViewport)
(princ)
)
; get boundingbox center
(defun GetBcent ( %e / ll ur)
(if (= (type %e) 'ENAME)(setq %e (vlax-ename->vla-object %e)))
(cond
; get the centerpoint from boundingbox
((and (vlax-method-applicable-p %e 'getboundingbox)
(not (vl-catch-all-error-p (vl-catch-all-apply 'vla-getboundingbox (list %e 'll 'ur)))))
(mapcar (function (lambda (a b) (/ (+ a b) 2.)))(vlax-safearray->list ll)(vlax-safearray->list ur)))
; else get alignment or point
((and (vlax-method-applicable-p %e 'alignment)(= (vla-get-alignment %e) 1))
(reverse (cdr (reverse (vlax-safearray->list (vlax-variant-value (vla-get-TextAlignmentPoint %e)))))))
(t (reverse (cdr (reverse (vlax-safearray->list (vlax-variant-value (vla-get-InsertionPoint %e)))))))
)
)