1

所以,我必须创建一个宏来运行报告,并将所有具有相同发票编号的记录放在一行中,其中包含日期、销售对象、同一张发票的所有行的总和编号的扩展定价、订单运费(如果适用)以及扩展定价和订单运费的总和。

它将采用这些值并将它们放入新表中。

这是我遇到问题的地方。在大多数情况下,宏似乎可以工作,但是一旦到达某个记录,它实际上将编号的发票(即(123456)更改为下一行的发票(即 123457)因此,123456 的发票不再是存在,而是与 123457 组合在一起。

我逐步完成了它,单元格应该没有理由改变值,因为它没有对任何其他单元格进行更改。有没有人有理由解释这样做的原因?

这是我的代码。提前致谢。

    Sub CombineInvoice()

    Dim InvoiceNum As String, InvoiceDate As String, SoldToAcct As String
    Dim ExtPrice As Double, OrderFreight As Double, OrderTotal As Double
    Dim WS2 As Worksheet

    Application.ScreenUpdating = False

    Set WS2 = Sheets.Add

    With Sheet1.Range("A1,C1,D1,BB1,BD1")
        .Copy Destination:=Sheet2.Range("A1:F1")
    End With

    Sheet1.Select

    InvoiceNum = Range("A2").Value
    InvoiceDate = Range("C2").Value
    SoldToAcct = Range("D2").Value

    Sheet2.Select
    Selection.Offset(0, 5).Value = "Order Total"
    Range("A2").Select
    Sheet1.Select
    Range("A2").Select

    Do
        'Set order freight
        OrderFreight = OrderFreight + Selection.Offset(0, 55)
        'Set invoice date
        InvoiceDate = Selection.Offset(0, 2)
        'Set Sold to account
        SoldToAcct = Selection.Offset(0, 3)
        'Get extended price
        Do Until Selection.Value <> InvoiceNum
            ExtPrice = ExtPrice + Selection.Offset(0, 53)
            'Make sure orderFreight is the same
            If (OrderFreight <> OrderFreight Or OrderFreight = 0) Then
                OrderFreight = OrderFreight + Selection.Offset(0, 55)
            Else
                OrderFreight = OrderFreight
            End If

            Selection.Offset(1, 0).Select
        Loop
        'Add Extended Price to Order Freight
        OrderTotal = ExtPrice + OrderFreight
        'Populate Sheet 2 with data
        Sheet2.Select
        With Selection
             .Value = InvoiceNum
             .Offset(0, 1).Value = InvoiceDate
             .Offset(0, 2).Value = SoldToAcct
             .Offset(0, 3).Value = ExtPrice
             .Offset(0, 4).Value = OrderFreight
             .Offset(0, 5).Value = OrderTotal
             .Offset(1, 0).Select
        End With
        'Return to sheet 1 for next invoice number
        Sheet1.Select
        Selection.Value = Selection.Offset(1, 0)
        InvoiceNum = Selection.Value
        ExtPrice = 0
        OrderFreight = 0
        If (Selection.Value = "") Then Exit Do

    Loop

    Application.ScreenUpdating = True

    End Sub
4

1 回答 1

0

在第一个/外循环结束时,我们有这些代码行:

Sheet1.Select
Selection.Value = Selection.Offset(1, 0)
InvoiceNum = Selection.Value
ExtPrice = 0
OrderFreight = 0
If (Selection.Value = "") Then Exit Do

OP 在评论中指出删除此行有效:

Selection.Value = Selection.Offset(1, 0)

但是,由于Selection.Value在下一行使用,我也建议对下一行进行以下更改(@Scott 在评论中也建议了这一点)。

InvoiceNum = Selection.Offset(1, 0).Value
于 2012-07-13T13:17:30.010 回答