[英]Excel VBA select range using cells and xlDown
我正在遍历 A 列中的一个范围以查找标题,一旦找到,我需要选择下一个单元格直到最后使用的单元格。
无法终生使用 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
,我将如何选择这个范围。
以下应该工作:
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.