首页 > 解决方案 > For循环工作但指责错误 - VBA

问题描述

我对下面的代码有一点问题。在粗线中,它指责“运行时错误'91':对象变量或未设置块变量”。有趣的是,一切正常,但我不希望它每次都显示此消息。有人知道如何解决吗?非常感谢

Private Sub applybutton_Click()
    
    variablesheet = "Cl" & box_id.Value
    maxrow = Sheets("Cl1").Range("A7").Value
    
    Dim i As Long  

    For i = 1 To maxrow
        If Sheets(variablesheet).Cells(i + 19, 1).Value = 0 Then
               flavorname = Sheets(variablesheet).Cells(i + 19, 2).Value
               **flavor_id = Sheets("products").Range("A:A").Find(flavorname).Offset(0,1).Value**
         Sheets(variablesheet).Cells(i + 19, 4).Value = Me.Controls(flavor_id).Value
        End If
    Next i

标签: vbaloopsfor-loopobjectruntime

解决方案


要控制 find nothing 错误,您的代码应该是这样的(并且以更具体的方式,查看值并查看整个搜索文本):

Private Sub applybutton_Click()
    
    variablesheet = "Cl" & "1" 'box_id.Value
    maxrow = Sheets("Cl1").Range("A7").Value
    
    Dim i As Long

    For i = 1 To maxrow
        If Sheets(variablesheet).Cells(i + 19, 1).Value = 0 Then
               flavorname = Sheets(variablesheet).Cells(i + 19, 2).Value
               With Sheets("products").Range("A:A")
                    Set c = .Find(flavorname,  LookIn:=xlValues, LookAt:=xlWhole)
                    If Not c Is Nothing Then
                        flavor_id = c.Offset(0, 1).Value
                        Sheets(variablesheet).Cells(i + 19, 4).Value = Me.Controls(flavor_id).Value
                    End If
                End With
        End If
    Next i

推荐阅读