根据通用 ID 搜索和列出单元格值
我已在名为Sheet1的电子表格中重新创建了您的数据
在Sheet2 我有一张只有标题的空白纸
当我点击Sheet1 上的按钮时,系统会提示我InputBox
在本例中,我将搜索 Prod ID 值为 1。以下是 Sheet2 上的结果
我可以多次重复此操作,结果页面会自动清除旧的搜索值,只列出新的搜索。
代码
将以下代码放入模块中。 FindAndShow 是您要分配给第一页上的按钮形状的宏,如果您希望像我一样设置自己。
Sub FindAndShow()
Dim ws As Worksheet: Set ws = ThisWorkbook.Sheets(1)
Dim wsResult As Worksheet: Set wsResult = ThisWorkbook.Sheets(2)
Dim prodID As String, prodRng As Range
Dim myRowOffset As Long, mySearch As String, nextRow As Long
'First is clearing old search items
wsResult.Range("A2", "D" & wsResult.Cells(wsResult.Rows.Count, "B").End(xlDown).Row).Clear
'Next we find the next blank row to start placing our results. As I have it, this will
'always be 2 because we're clearing old data. I've left it dynamic to make modifying the
'code easier.
nextRow = wsResult.Range("B2", wsResult.Cells(wsResult.Rows.Count, "B").End(xlUp)).Row + 1
'Here we take our input from the user.
'You can change the prompt and title to fit your needs.
prodID = InputBox("Which Production ID would you like to find?", "Production ID Search")
Set prodRng = ws.Range("A:A").Find(What:=prodID, LookIn:=xlValues, LookAt:=xlWhole)
'This is the loop that finds search items, and pastes them to the results page.
'Normally having range.value = range.value would be quickest, but since we're dealing with
'thousands of cells that are in sizable groups, the copy method will be most ideal.
If Not prodRng Is Nothing Then
wsResult.Range("A" & nextRow).Value = prodID
firstResult = prodRng.Address
Do
myRowOffset = FindRowOffset(prodRng)
ws.Range(prodRng.Offset(0, 1), prodRng.Offset(myRowOffset, 3)).Copy _
wsResult.Range("B" & nextRow)
Set prodRng = ws.Range("A:A").FindNext(prodRng)
nextRow = nextRow + myRowOffset + 1
Loop While Not prodRng Is Nothing And prodRng.Address <> firstResult
End If
End Sub
Function FindRowOffset(myRange As Range) As Long
'This functions only purpose is to see how far each search block goes.
Dim ws As Worksheet: Set ws = ThisWorkbook.Sheets(1)
Dim i As Long: i = 1
Do While myRange.Offset(i).Value = "" And myRange.Offset(i, 1) <> ""
i = i + 1
Loop
FindRowOffset = i - 1
End Function