VBA:find列标题后设置列范围
我希望能够设置一个范围的第二个单元格列标题,我正在寻找列的底部。 我不想select整个列,而只是从第二个单元格(不包括标题)开始使用的范围。
我能够写一些代码来查找标题,但是我有一些问题将单元格地址(string)转换为一个范围,然后为该列的其余部分select使用的范围。 这是我迄今为止:
Sub colRange() Dim ws As Worksheet Dim hostCellRange As Range Set ws = Worksheets("Sheet1") With ws With .Range("A1", .Cells(1, .Columns.Count).End(xlToLeft)) Set cfind = .Find(What:="host", LookIn:=xlValues, lookat:=xlWhole) If Not cfind Is Nothing Then hostCell = cfind.Address Set hostCellRange = ws.Range(hostCell) End If End With End With End Sub
感谢您的帮助!
正确的做法是
Option Explicit Sub colRange() Dim ws As Worksheet Dim hostCellRange As Range, cfind As Range Dim lRow As Long, lCol As Long Set ws = Worksheets("Sheet1") With ws With .Range("A1", .Cells(1, .Columns.Count).End(xlToLeft)) Set cfind = .Find(What:="host", LookIn:=xlValues, lookat:=xlWhole) If Not cfind Is Nothing Then '~~> Find the column number lCol = cfind.Column '~~> Find the last row in that column lRow = ws.Range(Split(Cells(, lCol).Address, "$")(1) & ws.Rows.Count).End(xlUp).Row '~~> Create the range Set hostCellRange = .Range(cfind.Offset(1, 0), cfind.Offset(lRow - 1, 0)) Debug.Print hostCellRange.Address End If End With End With End Sub
例1
例2
有趣阅读如何正确地find最后一行
尝试使用hostCellRange
中的Offset
设置hostCellRange
,则不需要该Address
。
If Not cfind Is Nothing Then Set hostCellRange = .Range(cfind.Offset(1, 0), cfind.End(xlDown)) End If
注意 : cfind.End(xlDown)
可以在中间没有空单元格的情况下工作。