debugging 如何避免编译错误:此代码中需要对象?

u3r8eeie  于 2023-10-24  发布在  其他
关注(0)|答案(1)|浏览(160)

我试图在每次字符串“YES”出现在F列时使用x创建一个运行计数器。我试图修复的代码是使用.Find和.FindNext函数搜索字符串,当搜索返回到相同的“YES”字符串时,使用if语句停止循环或函数。
出于某种原因,编译错误“object required”不断出现,即使我相信所有对象都被调用并且具有适当的对象限定符。
我一直尝试将对象改为不同的变量,反之亦然。以及尝试更改代码的格式。似乎没有工作。

Function Refill()
Dim x As Variant
Dim rg As Range
Dim search As Object
Dim search1 As Object
Dim search2 As Object
   
Set x = 0
Set Refill = 0
Set rg = Range("F:F")
Set search = rg.Find("YES")

If Not search Is Nothing Then
    x = 1
    Refill = x
    Set search1 = rg.FindNext(search)
    MsgBox (search1.Row)
    If search1.Row = search.Row Then Exit Function
    
    Do
    If Not search1 Is Nothing Then
        x = x + 1
        Refill = x
        Set search2 = rg.FindNext(search1)
        If search2.Row = search1.Row Then Exit Do
    End If
    Loop  
End If
End Function
t3irkdon

t3irkdon1#

这是在循环中使用Find/FindNext的一般模式:

Sub Tester()
    
    Dim rg As Range, f As Range, addr As String, x As Long
    
    Set rg = ActiveSheet.Range("F:F") 'be explicit about which worksheet
    'Provide all important arguments for the first Find(),
    ' in case a previous call set something you *don't* want
    Set f = rg.Find("YES", after:=rg.Cells(rg.Cells.CountLarge), lookat:=xlWhole, _
                    SearchDirection:=xlNext, MatchCase:=False)
    
    If Not f Is Nothing Then                  'got a match?
        addr = f.Address                      'remember the location
        Do
            x = x + 1                         '...or do something with `f`
            
            Set f = rg.FindNext(f)            'any more matches?
            If f Is Nothing Then Exit Do      'no more matches
            If f.Address = addr Then Exit Do  '...or we looped back around
        Loop
    End If
    
    Debug.Print x
    
End Sub

相关问题