假设我有一组给定的列标题,我只知道列标题名称。 我只想检索列名称,例如我在搜索列名称" Text"它位于单元格A中,然后我想要A作为我的结果,但它给了我1.任何人都可以帮助我。
这是我的代码
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
答案 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
答案 1 :(得分:0)
使用您获得的列号以及包含标题的行:
Cells(headerRowNumber,colNumber).value