【问题标题】:Object required error on Range Is Nothing?Range Is Nothing 上的 Object required 错误?
【发布时间】:2021-03-16 15:53:44
【问题描述】:

我在 VBA 中有一些代码,它试图根据活动工作表的特定列中的值对行进行分组。我看到的问题是在线If rngArea Is Nothing Then 它给了我

424:需要对象

错误。

我想我已经正确地将rngArea 变量声明为Range,如果这个变量最初是空的,那么Is Nothing 是正确的,对吧?这么简单的一行代码,我看不出还有什么问题。

有人可以帮忙吗?

Sub GroupEpics()
    FTESheet.Activate
    
    Dim c, rngArea, EpicLink As Range
    
    LstRow = FTESheet.Cells(Rows.Count, "B").End(xlUp).Row
    Set EpicLink = FTESheet.Range(Cells(3, 4), Cells(LstRow, 4))
    
    'undo any existing groupings
    'suppress error if no rows are grouped
    On Error Resume Next
    Range("A1:A" & LstRow).Rows.Ungroup
    On Error GoTo 0
    
    'loop through all epic link values
    For Each c In EpicLink
        If c.Value <> 0 And c.Row() > 2 Then
            'add this epic row to the cumulative range
            If rngArea Is Nothing Then
                Set rngArea = c
            Else
                Set rngArea = Union(rngArea, c)
            End If
        End If
    Next c
    
    ' loop through Range's Areas and group each one of them
    For Each c In rngArea.Areas
        c.EntireRow.Group
    Next c
End Sub

【问题讨论】:

    标签: excel vba


    【解决方案1】:

    其实问题是你没有声明rngArea As Range

    如果你声明

    Dim c, rngArea, EpicLink As Range
    

    这实际上意味着

    Dim c As Variant, rngArea As Variant, EpicLink As Range
    

    在 VBA 中,您需要为 每个 变量指定一个类型,否则默认为 Variant

    Dim c As Range, rngArea As Range, EpicLink As Range
    

    因此,如果您不将rngArea 设置为对象,则它只是一个空的Variant,但不是对象,但Is Nothing 正在检查对象,这就是它失败的原因。

    如果您声明Dim rngArea As Range,您将变量定义为范围对象。所以如果没有设置它是Nothing,因此可以用If rngArea Is Nothing Then进行测试。

    【讨论】:

      【解决方案2】:

      需要将 rngArea 声明为 Range(下)

      Dim c, rngArea As Range, EpicLink As Range
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2019-09-24
        • 1970-01-01
        • 2018-01-25
        • 2020-07-26
        • 1970-01-01
        • 2017-05-08
        • 2022-01-08
        相关资源
        最近更新 更多