选择标题下具有值的所有单元格

时间:2016-03-09 21:14:10

标签: excel vba

我有一个代码,用于选择具有"地址"的列。头。

Sub FindAddressColumn()
  Dim rngAddress As Range
  Set rngAddress = Range("A1:Z1").Find("Address")
  If rngAddress Is Nothing Then
    MsgBox "Address column was not found."
    Exit Sub
  End If
  Range(rngAddress, rngAddress.End(xlDown)).Select
End Sub

我想选择第2行或标题后面的行"地址"一直到最后一行有价值。

2 个答案:

答案 0 :(得分:2)

使用WorksheetFunction object MATCH function在第一行中找到列标题标签。

Sub FindAddressColumn()
    dim cl as long
    with worksheets("Sheet1")
        if not iserror(application.match("address", .rows(1), 0)) then
            cl = application.match("address", .rows(1), 0)
            .range(.cells(2, cl), .cells(rows.count, cl).end(xlup)).select
        else
            MsgBox "Address column was not found."
            Exit Sub
        end if
    end with
End Sub

我更喜欢从下往上查找列中最后一个填充的单元格,但如果您希望从上到下查看,则可以轻松修改上述代码以适应。

Range .Select¹方法并不总是引用个人或Range object组的最可靠方法。使用With ... End With statement直接引用父工作表应该会有所帮助。

¹有关远离依赖选择和激活以实现目标的更多方法,请参阅How to avoid using Select in Excel VBA macros

答案 1 :(得分:2)

如果您的地址栏中有空格,请使用以下代码:

Sub FindAddressColumn()
  Dim rngAddress As Range, LastRow As Long
  Set rngAddress = Range("A1:Z1").Find("Address")
  If rngAddress Is Nothing Then
    MsgBox "Address column was not found."
  Else
    LastRow = Cells(Rows.Count, rngAddress.Column).End(xlUp).Row
    Range(Cells(2, rngAddress.Column), Cells(LastRow, rngAddress.Column)).Select
  End If
End Sub