VBA优化宏循环

时间:2016-04-06 10:03:51

标签: excel vba excel-vba macros

场景是我有40张纸,每张纸最多可以有大约5k行,所以我处理了很多数据,这导致这个宏运行得非常慢。例如,仅第一张纸具有大约15219162个计算,其仅具有约380行。有没有办法减少我的宏必须运行的计算量?

到目前为止,共有39326个unqiue twitter名称,这意味着第一页有39326 x 387行。

Sub CountInvestorsByTwitterName()
    With Application
        .Calculation = xlCalculationManual: .ScreenUpdating = False: .DisplayAlerts = False
    End With
    Dim row_total As Long
    Dim Unique_Values_Sheet As Worksheet
    Set Unique_Values_Sheet = Sheets(Sheets.Count)
    Unique_Values_Sheet.Columns("B:XFD").EntireColumn.Delete
    Dim Unique_Values_Sheet_row_total As Long
    Unique_Values_Sheet_row_total = Unique_Values_Sheet.Cells(Rows.Count, "A").End(xlUp).Row
    Dim Unqiue_Twitter_Names As Range
    Set Unqiue_Twitter_Names = Unique_Values_Sheet.Range("A2:A" & Unique_Values_Sheet_row_total).Cells
    For Each s In Sheets
        If s.Name <> "UNIQUE_DATA" Then
            row_total = s.Cells(Rows.Count, "B").End(xlUp).Row
            For Each r In s.Range("B2:B" & row_total).Cells
                    Twitter_Name = r.Value
                    For Each c In Unqiue_Twitter_Names
                        If c.Value = Twitter_Name Then
                            With c
                                .Offset(0, 1).Value = CDbl(.Offset(0, 1).Value) + 1
                                .End(xlToRight).Offset(0, 1).Value = s.Name
                            End With
                        End If
                    Next
            Next
        End If
        ' Loop through first sheet
'        Exit For
    Next
    With Application
        .Calculation = xlCalculationAutomatic: .ScreenUpdating = True: .DisplayAlerts = True
    End With
End Sub

2 个答案:

答案 0 :(得分:1)

试试这个

select
    SUBSTRING('India|Korea', 1, position('|' in 'India|Korea') - 1) as first,
    SUBSTRING('India|Korea', position(',' in 'India|Korea') + 1)as second

如果速度不够快,你可以尝试一些&#34; array&#34;方法,将相关的单元格值存储在数组中并使用它们进行搜索

字典方法也值得考察

答案 1 :(得分:0)

我会做什么:

1)清除整个'UNIQUE_DATA'表 2)循环遍历所有工作表,如果工作表的名称不是“UNIQUE DATA”,则将包含内容的所有行复制到“UNIQUE_DATA”(复制粘贴行,事先检测哪些行,以及在哪些行插入它们) )
3)对包含twitter句柄的列中的“UNIQUE DATA”中的所有行进行排序。如果您将宏录制一次,宏代码很容易理解 4)遍历工作表'UNIQUE_DATA'中的所有行,并将Twitter句柄的值与下面行的Twitter句柄进行比较。如果它们匹配,则删除下一行(并降低循环计数器的上限)。

你应该得到所有独特的Twitter句柄。 我不得不同意最后一步可能需要一些时间。但至少这样做是O(n)的复杂性,而不是你目前有两个嵌套循环的O(n²)。特别是对于n的高值,时间差应该是显着的。

相关问题