【问题标题】:Range Won't Define范围不会定义
【发布时间】:2018-07-13 22:20:25
【问题描述】:

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

我想要完成的事情:

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

Sample Cells to Understand Range to be Defined

所以范围将是上图中第 5 列中的 i+1 到 i+etc 行

谢谢

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))

【问题讨论】:

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


    【解决方案1】:
    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
    

    【讨论】:

    • 谢谢!这很有帮助
    【解决方案2】:

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

    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
    

    【讨论】:

    • 谢谢!这很有帮助
    猜你喜欢
    • 2010-12-03
    • 1970-01-01
    • 1970-01-01
    • 2013-01-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多