答案 0 :(得分:3)
让我们假设:
Headers
出现在第一行代码:
Option Explicit
Sub test()
Dim LastColumn As Long, LastRow As Long
Dim IDColumnNo As Range, DateColumnNo As Range, IDposition As Range
Dim strID As String
Dim dtDate As Date
'Set the ID you want to search for. Change to fullfil you needs
strID = "w"
With ThisWorkbook.Worksheets("Sheet1")
'Find the last row of the first column
LastRow = .Cells(.Rows.Count, "A").End(xlUp).Row
'Find the last column of the first row
LastColumn = .Cells(1, .Columns.Count).End(xlToLeft).Column
'Find which is the column with the IDs searching for the Header "ID"
Set IDColumnNo = .Range(.Cells(1, 1), .Cells(LastRow, LastColumn)).Find("ID", LookIn:=xlValues, Lookat:=xlWhole)
'Find which is the column with the Dates searching for the Header "Date"
Set DateColumnNo = .Range(.Cells(1, 1), .Cells(LastRow, LastColumn)).Find("Date", LookIn:=xlValues, Lookat:=xlWhole)
If Not IDColumnNo Is Nothing And Not DateColumnNo Is Nothing Then
'Find which the Id we want"
Set IDposition = .Range(.Cells(2, IDColumnNo.Column), .Cells(LastRow, IDColumnNo.Column)).Find(strID, LookIn:=xlValues, Lookat:=xlWhole)
If Not IDposition Is Nothing Then
dtDate = .Cells(IDposition.Row, DateColumnNo.Column).Value
Else
MsgBox "ID is missing!"
End If
Else
MsgBox "ID, Date or both headers are missing!"
End If
End With
End Sub
答案 1 :(得分:1)
假设您需要查找名为“ ID”的列并从“状态”列返回值,则可以使用以下公式
=OFFSET(INDIRECT(ADDRESS(1,MATCH("ID",A1:E1,0))),MATCH(K1,OFFSET(INDIRECT(ADDRESS(1,MATCH("ID",A1:E1,0))),1,0,100,1),0),MATCH("Status",A1:E1,0)-MATCH("ID",A1:E1,0),1,1)
要查找的值在单元格K1
您会看到,如果在上面的屏幕截图中将“状态”列移至“ D”列,则K2中返回的“状态”值将不同
只是为了好玩,我将A列的名称更改为Status,现在公式从该列返回了值
所以它似乎很通用:)
答案 2 :(得分:0)
将数据转换为表格。您现在的数据有点像这样:
要在Excel中快速创建表,请执行以下操作:
使用表的技巧是,即使添加/删除列,列ID也会与特定名称相关联。每个列范围的名称都是标题本身。
因此,在执行此操作后,要获取与给定ID相关联的日期,可以在单元格(表外)中使用此公式。我知道了:
我用来获取给定ID日期的公式是:
=INDEX(Table1[Date];MATCH(I2;Table1[ID];0))
使用表的好处是,即使添加或删除列,公式也将起作用,即使您更改标题的名称,它也将起作用!
如您在上图中所见,该公式可以完美地运行,甚至可以更改所有内容。
注意:只要找到ID,该公式就会起作用。如果找不到ID,则会返回错误。另外,它将找到第一个巧合,因此如果给定的ID是重复的,它将返回第一个巧合的日期。