2016-06-18 9 views
0

与えられた列ヘッダーセットがあり、列ヘッダー名のみがわかっているとします。 カラム名を取得するだけです。たとえば、カラム名 "Text"を検索していて、それがセルAにある場合、Aを結果として返したいのですが、誰かが助けてくれますか?ここで既知の列ヘッダー名で列値を取得する方法

は尖った@newguy私のコード

Sub searchHeader() 

columnNamesRow = 1   ' or whichever row your names are in 
nameToSearch = "Text"  ' or whatever name you want to search for 
columnToUse = 0 
lastUsedColumn = Worksheets("Sheet1").Cells(1, Worksheets("Sheet1").Columns.Count).End(xlToLeft).Column 

For col = 1 To lastUsedColumn 
    If Worksheets("Sheet1").Cells(columnNamesRow, col).Value = nameToSearch Then 
     columnToUse = col 
    End If 
Next col 


If columnToUse > 0 Then 
' found the column you wanted, do your thing here using "columnToUse" as the column index 
MsgBox columnToUse 
End If 
End Sub 
+1

ここでこの[関数](http://stackoverflow.com/questions/12796973/function-to-convert-column-number-to-letter)を使用してください。 – newguy

+0

ありがとうございました! –

答えて

0

機能ですとにかく、それはあなたが考慮するのを助けることができる答え

です:Rangeオブジェクトの

  • 使用Find()方法の代わりに、細胞をループする。

が好きな特定のニーズに合わせて、その関数のコアを使用すると、次の次のよう

Option Explicit 

Function searchHeader(shtName As String, nametosearch As String, headersRow As Long) As String 
    Dim f As Range 

    With Worksheets(shtName) 
     Set f = .Range(.Cells(headersRow, 1), .Cells(headersRow, .Columns.Count).End(xlToLeft)).Find(what:=nametosearch, LookIn:=xlValues, lookat:=xlWhole) 
    End With 

    If Not f Is Nothing Then searchHeader = Split(f.Address, "$")(1) 
End Function 

を使用する:

Sub main() 

    MsgBox """Text"" is the header of column """ & searchHeader("Sheet1", "Text", 1) & """" 

End Sub 
0

は列の番号を使用します取得した行と、ヘッダーを含む行:

Cells(headerRowNumber,colNumber).value 
関連する問題