VBA-将循环内的地址存储为新的范围变量

Yol*_*ken 1 excel vba

我试图在循环内获取单元格的新范围,并在当前代码中收到以下错误:

未设置对象变量或带块变量

这是我的代码,我尝试忽略问题。错误来自top= ...

Private Sub test_sub()


    Dim rngReference As Range, b As Range, top as Range
    Dim top As Range

    Set rng= Workbooks("file.xlsx").Worksheets(1).Columns(1)

    For Each b In rng= 
    ' Look for cell that meets criteria
        If InStr(1, b.Text, "THIS CELL") > 0 Then
        ' Store offset of current cell as new range
            top = Range(b.Offset(1, 1).Address)

            Debug.Print b.Address; b.Offset(1, 1).Address; top 
        End If

    Next b

End Sub
Run Code Online (Sandbox Code Playgroud)

Tim*_*ams 7

丢失Set(将值分配给对象类型变量时,这是必需的):

Set top = Range(b.Offset(1, 1).Address)
Run Code Online (Sandbox Code Playgroud)

但会更好

Set top = b.Offset(1, 1)
Run Code Online (Sandbox Code Playgroud)

b.Offset(1, 1)已经是一个Range对象,因此无需将其转换为Address,然后再转换回Range