2016-05-13 200 views
1

我正在循环遍历A列中的范围以找到标题,一旦找到需要选择下一个单元格到最后一个使用的单元格。使用Excel VBA使用单元格和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))细胞和end(xlDown)

不能为我的生命选择此范围内,但没有组合将正常工作。

有在A列中的空白单元格,数据的一个例子是这样:

MONTH 
Jan 
Feb 

AGE 
18-21 
22+ 

GENDER 
Male 
Female 
Horse 

我怎么会去选择这个范围内,如果rangeName是等于GENDER例如。

回答

1

下面应该工作:

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 
+0

谢谢你的答案和额外的信息,这是行得通的,我对你提供的显式样本给予了高度的评价。 –

相关问题