3

ヘッダーに基づいて列を選択する次のコードがあります。

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

ヘッダーもリストに含まれていることがわかります。

ヘッダーに基づいて列を選択し、そこからヘッダー要素を削除する方法を知りたい.

4

2 に答える 2

4

これを試して

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

ただし、注意が必要です。xlDown2 行目以降のデータがない場合、予期しない結果が生じる可能性があります。また、あなたが取っているアプローチでは、名前が見つからない場合にエラーが発生します。

そうは言っても、ここに代替案があります

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
于 2013-04-15T11:24:12.960 に答える