2016-06-18 5 views
0

주어진 열 머리글 집합이 있고 열 머리글 이름 만 알고 있다고 가정 해보십시오. 방금 ​​열 이름을 검색하고 싶습니다. 예를 들어 "텍스트"라는 열 이름을 찾고 셀 A에 있습니다. 그런 다음 결과를 A로 지정하고 싶지만 아무에게도 도움을 줄 수는 없습니다. 여기 알려진 열 헤더 이름을 사용하여 열 값을 얻는 방법

내 코드입니다

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

여기 [Function] (http://stackoverflow.com/questions/12796973/function-to-convert-column-number-to-letter)를 사용하면 도움이되기를 바랍니다. – newguy

+0

감사합니다. –

답변

0

@newguy 지적 기능은 당신이 생각하는 데 도움이 될 수 있습니다 어쨌든

답변입니다 :

  • 사용 Find() 방법 객체 대신 Range의에게 세포를 통한 루핑

이 좋아하는 사용자의 특정 요구에 그 함수의 핵심를 사용하는 것은 다음 다음과 같이

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 
관련 문제