使用VBA在页面中打印多张发票,并仅为部分客户打印发票

时间:2019-10-11 02:11:50

标签: excel vba

发票模板图片

Invoice Template Image

我正在使用上面的模板在Excel中打印发票,其中模板的详细信息是从工作表中提取的,每一行都包含单个发票的详细信息。

每个页面都有两个发票,我想对其进行设置,以便一次只能打印特定客户的发票。客户名称为wks1.Cells(i, 6).Value

我尝试在If循环中使用简单的For语句,但是无论我做什么,只有相关客户打印页面上的第一张发票。第二张发票为空。

使用自定义过滤器并仅选择我要为其打印发票的客户无济于事,因为无论过滤器如何,代码都会处理每一行。我不在乎被硬编码到VBA中的客户名称。

我只希望基于wks1.Cells(i, 6).Value值顺序打印页面上的两个发票。

这是我的代码

Sub Button1_Click()
Dim wks1 As Worksheet, wks2 As Worksheet

// Data Source
Set wks1 = Sheets("Data")
// Invoice Template
Set wks2 = Sheets("Template")

Dim i As Integer

LastRow = Cells(Rows.Count, "A").End(xlUp).Row

For i = 2 To LastRow
    // Make a temporary working copy
    wks2.Copy After:=Sheets(Sheets.Count)
    ActiveSheet.Name = "wks3"

    Set wks3 = Sheets("wks3")

    // Fill the details for the first invoice in the page

    wks3.Range("C3").Value = wks1.Cells(i, 1).Value
    wks3.Range("C5").Value = wks1.Cells(i, 2).Value
    wks3.Range("F14").Value = wks1.Cells(i, 3).Value & " days at " & ChrW(&H20B9) & " " & wks1.Cells(i, 4).Value & " per day "
    wks3.Range("C7").Value = wks1.Cells(i, 5).Text
    wks3.Range("I18").Value = wks1.Cells(i, 5).Text
    // wks1.Cells(i, 6).Value = Customer Name
    wks3.Range("C9").Value = " " & wks1.Cells(i, 6).Value
    wks3.Range("C12").Value = " " & wks1.Cells(i, 7).Value
    wks3.Range("C14").Value = wks1.Cells(i, 8).Value
    wks3.Range("C16").Value = wks1.Cells(i, 9).Value
    wks3.Range("C18").Value = wks1.Cells(i, 10).Value
    wks3.Range("D21").Value = wks1.Cells(i, 11).Value

    // Increment "i" to process the next row in the Data Source worksheet
    i = i + 1

    // Fill the details for the second invoice in the page

    wks3.Range("C27").Value = wks1.Cells(i, 1).Value
    wks3.Range("C29").Value = wks1.Cells(i, 2).Value
    wks3.Range("F38").Value = wks1.Cells(i, 3).Value & " days at " & ChrW(&H20B9) & " " & wks1.Cells(i, 4).Value & " per day "
    wks3.Range("C31").Value = wks1.Cells(i, 5).Text
    wks3.Range("I42").Value = wks1.Cells(i, 5).Text
    // wks1.Cells(i, 6).Value = Customer Name
    wks3.Range("C33").Value = " " & wks1.Cells(i, 6).Value
    wks3.Range("C36").Value = " " & wks1.Cells(i, 7).Value
    wks3.Range("C38").Value = wks1.Cells(i, 8).Value
    wks3.Range("C40").Value = wks1.Cells(i, 9).Value
    wks3.Range("C42").Value = wks1.Cells(i, 10).Value
    wks3.Range("D45").Value = wks1.Cells(i, 11).Value

    // Save temporary working sheet as PDF
    wks3.Range("A1:L48").ExportAsFixedFormat Type:=xlTypePDF, _
        Filename:=ThisWorkbook.Path & "\pdf\" & wks1.Cells(i - 1, 1).Value & "-" & wks1.Cells(i, 1).Value

    // Delete temporary working sheet after PDF is saved
    Application.DisplayAlerts = False
    wks3.Delete
    Application.DisplayAlerts = True

    wks1.Activate

Next i

End Sub

1 个答案:

答案 0 :(得分:0)

还有另一种方法可以在不使用VBA的情况下填写第二张凭单。只需在第二张凭证的相关单元格中使用“ =”和单元格号即可。