创建摘要表(如何通过特定列和行的动态for循环处理数据)

时间:2018-01-15 15:22:49

标签: excel vba excel-vba

对于宏vba来说相当新,所以在一个中有多个问题 我想要创建的是一个总结。假设我有一个巨大的数据表 excel,为了清楚起见这里是一个摘录(仅用于illsutration,实际表格更大)

Chase_list

  A (Name)         B (Due)    C (Queries)     D (Comment)      
  Customer 1       50 464     20 000          Long-time debtor
  Customer 2        3 159     0               Resent invoice
  Customer 1       15 000     0               
  Customer 4       18 000     3 200           Promised payment

所以让我说我得到了这组数据,现在我想要创建一个函数来遍历表中的每个单元格,如果到期和查询的总和(列B和C)大于20 000将公司写入汇总表(在新工作表上)

这是我到目前为止所拥有的

Private Sub CommandButton1_Click()

  Dim chase_list As Worksheet
  Dim summary_list As Worksheet
  Dim due As Range
  Dim query As Range
  Set chase_list = Sheets("Chase_list") ' the name of my data worksheet in example
  Set summary_list = Sheets("Summary_list") ' the name the sheet i want to output data to

  ' now i need to create a function that will add the query and due column together
  Dim current_row_sum As Range

  'Let's go through every due invoice and query
  For Each due In chase_list.UsedRange.Columns("B")
    For Each query In chase_list.UsedRange.Columns("C")
        current_row_sum = WorksheetFunction.Sum(due, query)
        If (current_row_sum >= 20000) Then
            ' now i somehow need to create a loop that will basically add a new line every time a value is added, but I do not know how
            ' I know I could set it through Range("").Value = field, issue is, I don;t want to put it in a stationary cell, but on new line for each new value
        End If
    Next query
   Next due


End Sub

代码可能存在更多问题,因为我是vba的新手,虽然我有一些编码经验

预期输出

Summary_list

  A (Name)         B (Total)   C (Comment)        
  Customer 1       70 464      Long-time Debtor               
  Customer 4       21 200      Promised Payment       

我知道这不是一个特定的答案,对不起,但将它分成几部分是很困难的。提前谢谢

1 个答案:

答案 0 :(得分:1)

如下所示,假设您已经有了第二张摘要表:

Sub foo()
Dim ws As Worksheet: Set ws = Sheets("Sheet1")
Dim wsResult As Worksheet: Set wsResult = Sheets("Sheet2")
'declare and set your worksheet, change as required
LastRow = ws.Cells(ws.Rows.Count, "A").End(xlUp).Row
'find the last row with data on column A

For i = 2 To LastRow
'loop from row 2 to last
    If ws.Cells(i, 2) + ws.Cells(i, 3) > 20000 Then 'if Column 2 (ie B) + Column 3 (ie C) > 20000 then
        ResultFreeRow = wsResult.Cells(wsResult.Rows.Count, "A").End(xlUp).Row + 1 'find the next free row on Result Sheet
        ws.Rows(i).Copy wsResult.Rows(ResultFreeRow) 'copy row to next free row
    End If
Next i

End Sub