Forum Discussion

Jeremy_82's avatar
Jeremy_82
Copper Contributor
Mar 25, 2020
Solved

How To - 1 Worksheet "gets" the data, another worksheet displays it for printing.

Hello - I have a problem, and I'm not sure how to make it easier for the "end user". I have a workbook with a "Packing Slip" template in worksheet 1, it's specific to a customer and we put it in exce...
  • mtarler's avatar
    Mar 25, 2020

    Jeremy_82there may be a couple of solutions but the best I can say is make all fields on sheet 1 look up the correct value on sheet 2 based on the order #.  Then have a macro loop through all the order numbers, update sheet 1, and print that sheet.

    here is sample VBA code, a mix of code I already have/use and some that I whipped up for you.  It should work:

    Sub Print_All()

      dim invoiceNumber, invoiceRange as range

     set invoiceRange = Worksheet2.range("range of invoice numbers")

      For each invoiceNumber in invoiceRange

        Worksheet1.range("invoce number cell") = invoiceNumber.value

        call Print2PDF_Click()

      next

    end sub

     

    Sub Print2PDF_Click()
        Dim InvoiceDate
        Dim fname
        InvoiceDate = ActiveSheet.Cells(4, ActiveSheet.Range("$1:$10").Find("Invoice Date").Column + 1)
        fname = ActiveWorkbook.Path
        fname = CleanFileName(fname)
        fname =  fname & "_" & Date$
        Dim lastrow
        Dim lastcol
        lastrow = ActiveSheet.Range("$a:$a").Find("Grand Total", , xlValues).Row()
        lastcol = ActiveSheet.Cells(1, 1).Offset(0, 1).Column()
        With ActiveSheet.PageSetup
            .PrintArea = "$a$2:$" & Chr(95 + lastcol) & "$" & lastrow
            .Zoom = False
            .Orientation = xlLandscape
            .FitToPagesWide = 1
            .FitToPagesTall = False
        End With
        On Error GoTo FileDialog
        Call ActiveSheet.ExportAsFixedFormat(xlTypePDF, fname, xlQualityStandard, True, False, 1, , False)
        Exit Sub
    FileDialog:
        fname = InputBox("There was a problem saving the file.  Please make sure the path exists " & _
            "and the filename does not have any illegal characters (<,>,:,"",/,\,|,?,*). " & _
            "Please review and enter a corrected name & path for the file", "Filename/Path Error", fname)
        On Error GoTo FileDialog
        If fname <> "" Then
            Resume
        End If
    End Sub

    Function CleanFileName(fname, Optional inchar = "-")
    'This function will replace bad characters in a filename with inchar
        Dim badchars
        badchars = Array("<", ">", ":", """", "/", "\", "|", "?", "*")
        For Each badc In badchars
            fname = Replace(fname, badc, inchar)
        Next
        CleanFileName = fname
    End Function