【问题标题】:VBA: Setting column range after finding column headerVBA:找到列标题后设置列范围
【发布时间】:2017-11-25 00:14:01
【问题描述】:

我希望能够为我正在搜索的列标题下的第二个单元格设置一个范围到列的底部。我不想选择整个列,而只是从第二个单元格开始使用的范围(不包括标题)。

我能够编写一些代码来查找标题,但是在将单元格地址(字符串)转换为范围然后为该列的其余部分选择使用的范围时遇到了一些问题。这是我目前的情况:

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

感谢您的帮助!

【问题讨论】:

  • 你的范围内会有空白单元格吗?

标签: vba excel


【解决方案1】:

正确的做法是

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

Interesting Read on how to find the last row correctly

【讨论】:

  • 嗨,Siddharth,感谢您花时间解释代码!我会用这个!感谢您的帮助!
【解决方案2】:

尝试使用cfind 中的Offset 设置hostCellRange,您不需要Address

If Not cfind Is Nothing Then
    Set hostCellRange = .Range(cfind.Offset(1, 0), cfind.End(xlDown))
End If

注意cfind.End(xlDown) 将适用于中间没有空单元格的范围。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-09-27
    相关资源
    最近更新 更多