循环遍历列,同时汇总列数

时间:2018-01-12 11:38:15

标签: excel vba excel-vba loops

场景:我正在尝试遍历一些工作表,并且每个I循环遍历各行。当我循环工作表时,我还将列粘贴到摘要表中,然后从摘要工作表的下一个空行开始粘贴它。

问题:我尝试使用for循环中的行变量总和进行解决方案,但它不起作用。我想,由于它会在每个工作表中重置变量,因此最终会将数据粘贴到摘要中其他已填充的行上。

代码:

Option explicit
Sub Source_Cleaner()

Dim wb As Workbook
Dim ws As Worksheet
Dim zz As Long, lrowsum As Integer

ThisWorkbook.Activate
Set wb = ThisWorkbook

'Optimize Macro Speed Start
Application.ScreenUpdating = False
Application.EnableEvents = False
Application.Calculation = xlCalculationManual

lrowsum = 0

For Each ws In wb.Worksheets

    If ws.Name <> "Summary" Then

        For zz = 1 To ws.UsedRange.Rows.Count      
            If CBool(InStr(ws.Range("A" & zz).Value, "C")) Then                
                'Gathering to Summary
                wb.Sheets("Summary").Cells(zz + lrowsum, 1) = ws.Cells(zz, 1) 
                wb.Sheets("Summary").Cells(zz + lrowsum, 2) = ws.Cells(zz, 2) 

            ElseIf CBool(InStr(ws.Range("A" & zz).Value, "O")) Then
                'Gathering to Summary
                wb.Sheets("Summary").Cells(zz + lrowsum, 1) = ws.Cells(zz, 1) 
                wb.Sheets("Summary").Cells(zz + lrowsum, 2) = ws.Cells(zz, 2) 

            End If
            lrowsum = zz
            Next zz

End If
Next ws

'Optimize Macro Speed End
    Application.ScreenUpdating = True
    Application.EnableEvents = True
    Application.Calculation = xlCalculationAutomatic

End Sub

OBS:在这段代码中,我制作了lrowsum(这将是行的总量,当我遍历工作表时,它们被求和),并且zz是工作表的行。在工作表的最后,我做了lrowsum = zz,并且在下一个循环中我将两者相加,这导致前面解释的错误。

问题:首先,有没有更好的方式直接发布到工作表的下一个空行?

问题2:如何在每个ws循环结束时对变量求和,得到正确的值?

1 个答案:

答案 0 :(得分:1)

您可以尝试这样的方法,尽管使用AutoFilter或Find并因此避免循环会更有效。

'rest of your code before and after
Dim n As Long
n = wb.Sheets("Summary").Cells(Rows.Count, 1).End(xlUp).Row + 1

For Each ws In wb.Worksheets
    If ws.Name <> "Summary" Then
        For zz = 1 To ws.UsedRange.Rows.Count
            If CBool(InStr(ws.Range("A" & zz).Value, "C")) Then
                'Gathering to Summary
                wb.Sheets("Summary").Cells(n, 1) = ws.Cells(zz, 1)
                wb.Sheets("Summary").Cells(n, 2) = ws.Cells(zz, 2)
                n = n + 1
            ElseIf CBool(InStr(ws.Range("A" & zz).Value, "O")) Then
                'Gathering to Summary
                wb.Sheets("Summary").Cells(n, 1) = ws.Cells(zz, 1)
                wb.Sheets("Summary").Cells(n, 2) = ws.Cells(zz, 2)
                n = n + 1
            End If
        Next zz
    End If
Next ws