Rather than debug yours this does what you want just compare, the only difference is it makes a PDF directory rather than delete files. As you can see used since 2014 This version uses Ghostscript and joins all the pdf's into 1 pdf as well as individuals.
Rather than delete I would delete the pdf files if exist can use (command "shell" "Del dwgpre\*.pdf")
mergepdfs.lsp
;Plots layouts by range
; By Alan H Feb 2014
(defun AH:pltlays ( / val1 val2 plotnames dwgname lendwg pdfname lay numlay numend dwgpre)
(SETVAR "PDMODE" 0)
(setvar "plottransparencyoverride" 2)
(setvar "fillmode" 1)
(setvar "textfill" 1)
(setq plotnames '())
; check that pdf directory exists
(setq dwgpre (strcat (getvar "dwgprefix") "\pdf"))
(if (= (vl-file-directory-p dwgpre) nil)
(vl-mkdir dwgpre)
)
(SETQ LAYOUTS (vla-get-Layouts (vla-get-activedocument (vlax-get-acad-object))))
(SETQ COUNT (- (VLA-GET-COUNT LAYOUTS) 1))
(if (not AH:getvalsm)(load "Multi Getvals.lsp"))
(setq vals (AH:getvalsm (list "Enter plot range" "Enter start tab number" 6 4 "1" "Enter end tab number" 6 4 (RTOS COUNT 2 0))))
(setq numlay (atoi (nth 0 vals)))
(setq numend (atoi (nth 1 vals)))
(setq len (+ (- numend numlay) 1))
(setq dwgname (GETVAR "dwgname"))
(setq lendwg (strlen dwgname))
(setq dwgname (substr dwgname 1 (- lendwg 4)))
(repeat len
(vlax-for lay LAYOUTS
(if (= numlay (vla-get-taborder lay))
(setvar "ctab" (vla-get-name lay))
) ; if
(setq pdfname (strcat dwgpre "\\" dwgname "-" (getvar "ctab") ".pdf" ))
) ; for
(setvar "textfill" 1)
(setvar "fillmode" 1)
(setvar "PLOTTRANSPARENCYOVERRIDE" 2)
(COMMAND "-PLOT" "Y" "" "dwg to Pdf"
"Iso full bleed A3 (420.00 x 297.00 MM)" "m" "LANDSCAPE" "N" "W" "-6,-6" "807,560" "1=2" "C"
"y" "Acad.ctb" "Y" "n" "n" "n" pdfName "N" "y"
)
(setq numlay (+ numlay 1))
(setq plotnames (cons pdfname plotnames))
) ; end repeat
(setq trgfile (strcat (getvar "dwgprefix") "pdf\\" dwgname "-D" (nth 0 vals) "-D" (nth 1 vals) ".pdf"))
(setq plotnames (reverse plotnames))
(IF (= (length plotnames) 1)
(princ)
(progn
(if (not combinepdf)(load "mergepdfs"))
(combinepdf gsExe plotnames trgFile )
)
)
) ; defun
(AH:pltlays)
(princ)
Multi GETVALS.lsp