基于VBA Excel中列标题的dynamic列select

我有以下代码来select一个基于标题的列。

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 

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

想要知道一种方法来select一个基于标题的列,然后从中删除标题元素。

尝试这个

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

但谨慎的话。 如果从第二行开始没有数据, xlDown会给你意想不到的结果。 如果名字没有find,你正在采取的方法会给你一个错误。

话虽如此,以下是另一种select

 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 

只是修订了悉达思的答案(这很好)。 此代码将遍历指定表中的所有行,直到find具有指定列标题的行:

 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 

只是想在以前的答案稍微改善! 这工作得很好。