【发布时间】:2019-08-21 18:06:47
【问题描述】:
【问题讨论】:
【问题讨论】:
让我们假设:
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
【讨论】:
假设您需要查找名为“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,公式现在返回该列的值
所以它似乎很通用:)
【讨论】:
将您的数据转换为表格。你现在的数据是这样的:
要在 Excel 中快速创建表格,请执行以下操作:
使用表格的技巧在于,即使您添加/删除列,列 ID 也会与特定名称相关联。每个列范围的名称就是标题本身。
因此,在执行此操作后,要获取与给定 ID 关联的日期,您可以在单元格中(表外)使用此公式。我得到了这个:
我用来获取给定 ID 日期的公式是:
=INDEX(Table1[Date];MATCH(I2;Table1[ID];0))
使用表格的好处是,即使添加或删除列,公式也可以使用,即使更改表头的名称,它也可以使用!
正如您在上图中所见,该公式完美运行,甚至可以更改所有内容。
注意:只要找到 ID,公式就会起作用。如果找不到 ID,则会返回错误。此外,它会找到第一个重合,所以如果给定的 ID 是重复的,它将返回第一个重合的日期。
【讨论】: