【问题标题】:Excel VBA - How to avoid a loop and use .find instead?Excel VBA - 如何避免循环并使用 .find 代替?
【发布时间】:2013-12-04 16:03:01
【问题描述】:

我已经为我的 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

谢谢!

【问题讨论】:

  • 我知道我们可以读取您当前的循环,但您的最终目标是什么,以便我们能够提供准确的解决方案?

标签: vba loops excel find


【解决方案1】:

这是你要找的吗?

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

【讨论】:

    猜你喜欢
    • 2015-04-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-03-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多