2013-04-15 74 views
2

我有以下代碼來根據標題選擇列。基於VBA中列標題的動態列選擇Excel

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

當嘗試使用此範圍,並設置x值的圖表

ActiveChart.SeriesCollection(5).XValues = rng1 

我看到標題太進來就行了。

想知道一種方法來選擇一個基於標題的列,然後從它刪除標題元素。

回答

2

試試這個

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 
+0

謝謝悉達思! –

+0

歡迎:) –

0

只是修訂亞洲時報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 

只是想在前面的回答略有提高!這工作得很好。

+0

或者,'Set aCell'行可以讀取如下,以便從當前表單中進行更加動態的拉取:'Set aCell = .Range(Cells(i,1),Cells(i,ActiveSheet.UsedRange .Columns.Count))。Find(What:= Name,LookAt:= xlWhole,MatchCase:= True)' – Shrout1