基于VBA Excel中列标题的动态列选择

时间:2013-04-15 11:12:09

标签: excel excel-vba vba

我有以下代码来选择基于标题的列。

Dim rng1 As Range
Set rng1 = Range(Range("A1:Z1").Find("Name"), Range("A1:Z1").Find("Name").End(xlDown))

尝试使用此范围并在图表上设置XValue时

ActiveChart.SeriesCollection(5).XValues = rng1

我看到标题也出现在列表中。

想知道一种基于标题选择列的方法,然后从中删除标题元素。

2 个答案:

答案 0 :(得分:3)

试试这个

Set rng1 = Range( _
                 Range("A1:Z1").Find("Name").Offset(1), _
                Range("A1:Z1").Find("Name").Offset(1).End(xlDown))

但是要小心谨慎。如果第二行以后没有数据,xlDown会给您带来意想不到的结果。如果找不到名称,你所采取的方法也会给你一个错误。

话虽如此,这里有另一种选择

Sub Sample()
    Dim ws As Worksheet
    Dim lRow As Long
    Dim aCell As Range, rng1 As Range

    '~~> Set this to the relevant worksheet
    Set ws = ThisWorkbook.Sheets("Sheet1")

    With ws
        '~~> Find the cell which has the name
        Set aCell = .Range("A1:Z1").Find("Name")

        '~~> If the cell is found
        If Not aCell Is Nothing Then
            '~~> Get the last row in that column and check if the last row is > 1
            lRow = .Range(Split(.Cells(, aCell.Column).Address, "$")(1) & .Rows.Count).End(xlUp).Row

            If lRow > 1 Then
                '~~> Set your Range
                Set rng1 = .Range(aCell.Offset(1), .Cells(lRow, aCell.Column))

                '~~> This will give you the address
                Debug.Print rng1.Address
            End If
        End If
    End With
End Sub

答案 1 :(得分:-1)

只是修改Siddharth的答案(非常好)。此代码将遍历指定工作表中的所有行,直到找到具有指定列标题的行:

Sub Sample()
Dim ws As Worksheet
Dim lRow As Long
Dim aCell As Range, rng1 As Range
Dim i As Integer

'~~> Set this to the relevant worksheet
Set ws = ThisWorkbook.Sheets("Sheet1")
i = 1

'Iterate through the rows until the target name is found
    For i = 1 To ActiveSheet.UsedRange.Rows.Count
        With ws
            '~~> Find the cell which has the name - build range with current iterator
            Set aCell = .Range("A" & i & ":Z" & i).Find("Name")

            '~~> If the cell is found
            If Not aCell Is Nothing Then
                'Set iterator equal to rows to satisfy For...Next
                i = ActiveSheet.UsedRange.Rows.Count
                 '~~> Get the last row in that column and check if the last row is > 1
                lRow = .Range(Split(.Cells(, aCell.Column).Address, "$")(1) & .Rows.Count).End(xlUp).Row

                If lRow > 1 Then
                    '~~> Set your Range
                    Set rng1 = .Range(aCell.Offset(1), .Cells(lRow, aCell.Column))

                    '~~> This will give you the address
                    Debug.Print rng1.Address
                End If
            End If
        End With
    Next i
End Sub

只想略微改进以前的答案!这很有效。

相关问题