首页 文章

Excel VBA使用单元格和xlDown选择范围

提问于
浏览
2

我循环遍历A列中的一个范围以找到 Headers ,一旦找到,我需要选择下一个单元格到最后一个使用过的单元格 .

不能为我的生活使用Cells和End选择这个范围(xlDown)

For k = 1 To lastCell
    If Cells(k, 1).Value = rangeName Then
        Range(Range(Cells(k + 1, 1)), Range(Cells(k + 1, 1)).End(xlDown)).Select
    End If
Next k

我试过 Range(Cells(k + 1, 1), Cells(k + 1, 1).End(xlDown)) ,但没有组合可行 .

A列中有空白单元格,数据示例如下:

MONTH
Jan
Feb

AGE
18-21
22+

GENDER
Male
Female
Horse

如果 rangeName 等于 GENDER ,我将如何选择此范围 .

1 回答

  • 2

    以下应该有效:

    For k = 1 To lastCell
        If Cells(k, 1).Value = rangeName Then
            Range(Cells(k + 1, 1), Cells(k + 1, 1).End(xlDown)).Select
        End If
    Next k
    

    但是,我建议您更明确地编写代码以确保其有效:

    With Worksheets("SheetYouAreWorkingOn")
        For k = 1 To lastCell
            If .Cells(k, 1).Value = rangeName Then
                .Range(.Cells(k + 1, 1), .Cells(k + 1, 1).End(xlDown)).Select
            End If
        Next k
    End With
    

    在空/新文件上测试您的示例数据:

    Public Sub tmpSO()
    
    Dim lastCell As Long
    Dim rangeName As String
    
    rangeName = "AGE"
    
    With Worksheets("Sheet1")
        lastCell = .Cells(.Rows.Count, 1).End(xlUp).Row
        For k = 1 To lastCell
            If .Cells(k, 1).Value = rangeName Then
                .Range(.Cells(k + 1, 1), .Cells(k + 1, 1).End(xlDown)).Select
            End If
        Next k
    End With
    
    End Sub
    

相关问题