Excel VBA - 如何避免循环并使用.find?

时间:2013-12-04 16:03:01

标签: excel vba loops excel-vba find

我已将此循环用于我的VBA代码,但在将其应用于整个数据集之后,处理和excel崩溃需要很长时间。我想避免循环遍历100,000多行和列...但我无法弄清楚如何

这是代码:

Sub Splitter_Step1()

Dim Brand, lastBrand, BrandList As Range
Set lastBrand = Sheets("RefList").Range("B1").End(xlDown)
Set BrandList = Sheets("RefList").Range("B1", lastBrand)

Dim Product, ProductList, lastProduct As Range
Set lastProduct = Sheets("Products").Range("G2").End(xlDown)
Set ProductList = Sheets("Products").Range("G2", lastProduct)

Dim Parent As Range
Dim Model As Range


For Each Brand In BrandList
For Each Product In ProductList
    Set Parent = Brand.Offset(0, -1)
    If InStr(1, Product, Brand, 1) And IsEmpty(Product.Offset(0, 1).Value) Then
        Product.Offset(0, 1).Value = Parent + Brand
    ElseIf Not IsEmpty(Product.Offset(0, 1).Value) Then
        If InStr(1, Product, Brand, 1) Then
        Product.Offset(0, 2).Value = "2"
        End If
    End If
Next Product
Next Brand

谢谢!

1 个答案:

答案 0 :(得分:0)

这是你在找什么?

For Each Brand In BrandList
    Set Parent = Brand.Offset(0, -1)
    Dim pos As Range
    Dim nextPos As Range
    Set pos = ProductList.Offset(-1, 0).Find(What:=Brand, LookIn:=xlValues, SearchOrder:=xlByRows, SearchDirection:=xlNext, MatchCase:= _
            False, SearchFormat:=False)
    While Not pos Is Nothing
        If IsEmpty(pos.Offset(0, 1).Value) Then
            pos.Offset(0, 1).Value = Parent + Brand
        Else
            pos.Offset(0, 2).Value = "2"
        End If
        Set nextPos = ProductList.FindNext(After:=pos)
        If nextPos.Row > pos.Row Then 'found new product for brand
            Set pos = nextPos
        Else 'found all occurences of that brand
            Set pos = Nothing
        End If
    Wend
Next Brand