范围无法定义

时间:2018-07-13 22:20:25

标签: vba excel-vba for-loop if-statement range

有人可以帮助我理解为什么最后一行没有显示吗?

我要完成的工作:

定义一个范围,该范围以包含“添加的信息/选项”的单元格下的行开始,以包含上一列中的值的最后一个单元格结束。包含“添加的信息/选项”的单元格是可变的。

Sample Cells to Understand Range to be Defined

因此范围将是上图第5列中的i + 1至i +等行

感谢<3

Dim KeyCells As Range
Dim i, j, iRow, a, b As Integer
    For i = 1 To 500 Step 1
    If Not Cells(i, 5).Value = "Added Info/Options" Then
        Exit Sub
    Else:
        a = i + 1
        For iRow = a To i + 20 Step 1
            If Len(Cells(iRow, 4)) > 0 Then
                j = i + iRow
            End If
        Next iRow
    End If
    Next i
    KeyCells = Range(Cells(a, 6), Cells(j, 6))

2 个答案:

答案 0 :(得分:0)

Dim f As Range, KeyCells As Range

With ActiveSheet

    Set f = .Rows(5).Find(What:="Added Info/Options", lookat:=xlWhole)
    If Not f Is Nothing Then
        Set f = f.Offset(1, -1)
        Set KeyCells = .Range(f, .Cells(.Rows.Count, f.Column).End(xlUp))
    Else
        Msgbox "Required header not found!"
    End If

End With

答案 1 :(得分:0)

循环慢。匹配速度很快,从底部向上看,可以轻松找到最后一个填充的单元格。

dim aio as variant, keyCells As Range

with worksheets("sheet1")
    aio = application.match("Added Info/Options", .columns(5), 0)
    if not iserror(aio) then
        set keyCells = .range(.cells(aio+1, "E"), .cells(.rows.count, "D").end(xlup).offset(0, 1))
    else
        debug.print "Added Info/Options not found"
    end if
end with