我的原始数据集非常简单。
A-AM
,每列都有一个列标题。一列中的序列号可能会在其他几列中重复出现。有超过一百万个条目,有超过七万个唯一序列号。
我在column A
的单独表格上订购了所有序列号。
我想要的是在column B
中填充数组中第一次出现的序列号的相应列标题,从左到右。如果可能的话,我希望在column C
中有一个类似的公式,显示单元格最后一次出现在列表中的列标题(从右到左)。
原始数据如下所示。 (A1:H7
)
1974 1975 1976 1977 1978 1979 1980 1981
20 160 240 278 436 360 1696 1772
23 162 242 279 438 404 1698 1774
24 168 244 280 440 760 1700 1782
26 170 246 282 444 1620 1702 1784
28 188 248 283 449 1622 1706 1786
30 190 250 284 450 1624 1708 1788
答案 0 :(得分:0)
试试这段代码:
Sub getOccurs()
Dim findVal As String
Dim wsUniqueSN As Worksheet
Dim rngUniqueSN As Range
Dim xlCell As Range
Dim wsTarget As Worksheet
Dim rngLastCell As Range
Dim rngTarget As Range
Dim rngFirstFound As Range
Dim rngLastFound As Range
Const notFound As String = "[ VALUE NOT FOUND!! ]"
Set wsUniqueSN = ThisWorkbook.Worksheets("UniqueSN")
Set wsTarget = ThisWorkbook.Worksheets("Data")
Set rngUniqueSN = wsUniqueSN.Range("A1", wsUniqueSN.Range("A" & wsUniqueSN.Columns.Count).End(xlUp))
Set rngLastCell = wsTarget.Range("H" & wsTarget.Rows.Count)
'Use this if all columns contain the same number of rows to speed up the operation
'Set rngLastCell = wsTarget.Range("H" & wsTarget.Rows.Count).End(xlUp)
Set rngTarget = wsTarget.Range("A2", rngLastCell)
For Each xlCell In rngUniqueSN
findVal = xlCell.Value
Set rngFirstFound = rngTarget.Find(What:=findVal, LookIn:=xlValues, LookAt:=xlWhole, _
MatchCase:=True, SearchOrder:=xlByColumns, After:=rngLastCell)
Set rngLastFound = rngTarget.Find(What:=findVal, LookIn:=xlValues, LookAt:=xlWhole, MatchCase:=True, SearchOrder:=xlByColumns, _
After:=rngLastCell, SearchDirection:=xlPrevious)
If Not rngFirstFound Is Nothing Then
xlCell.Offset(0, 1).Value = wsTarget.Cells(1, rngFirstFound.Column).Value
Else
xlCell.Offset(0, 1).Value = notFound
End If
If Not rngLastFound Is Nothing Then
xlCell.Offset(0, 2).Value = wsTarget.Cells(1, rngLastFound.Column).Value
Else
xlCell.Offset(0, 2).Value = notFound
End If
Next xlCell
MsgBox "Operation complete.", vbInformation
End Sub
调用您的数据工作表“数据”和包含唯一序列号UniqueSN的工作表,确保SN在A列中。 宏将遍历SN使用的范围,并以正向和反向顺序查找相应的条目,在列B和C中写入相应的列标题。