简体   繁体   中英

Check if an excel cell value exists on multiple other sheets - and if so return the name of the sheet it exists on in another column

The first two sheets of my workbook each contain a single column, column A, of approximately 2000 values. In addition to these two sheets I have 42 other sheets that each contain anywhere from 20-1500 values, also in a single column A.

For each of the ~2000 values in column A of sheets 1 and 2 I am trying to check if those values exist in any of the other 42 sheets. If so, I'd like the name of the sheet they exist in to show up in column B.

So:

IF sheet1.A1.value EXISTS IN sheet3.A:A
RETURN sheet3.name
ELSE IF sheet1.A1.value EXISTS IN sheet4.A:A
RETURN sheet4.name

etc...

Sub test()

Dim ws As Worksheet
Dim i As Integer
Dim fRange As Range

'Perform search for Sheet1
Set ws = Sheets("Sheet1")

i = 3

While i <= ActiveWorkbook.Sheets.Count

ws.Select
Set fRange = Range("A1")
fRange.Select

While fRange.Value <> ""

Sheets(i).Select
Range("A1").Select

While ActiveCell.Value <> ""

If ActiveCell.Value = fRange.Value Then

fRange.Offset(0, 1).Value = Sheets(i).Name
ActiveCell.Offset(1, 0).Select

Else

ActiveCell.Offset(1, 0).Select

End If

Wend

Set fRange = fRange.Offset(1, 0)

Wend

i = i + 1

Wend

'Perform search for Sheet2
Set ws = Sheets("Sheet2")

i = 3

While i <= ActiveWorkbook.Sheets.Count

ws.Select
Set fRange = Range("A1")
fRange.Select

While fRange.Value <> ""

Sheets(i).Select
Range("A1").Select

While ActiveCell.Value <> ""

If ActiveCell.Value = fRange.Value Then

fRange.Offset(0, 1).Value = Sheets(i).Name
ActiveCell.Offset(1, 0).Select

Else

ActiveCell.Offset(1, 0).Select

End If

Wend

Set fRange = fRange.Offset(1, 0)

Wend

i = i + 1

Wend

End Sub

Use a For Each loop on the worksheets collection to cycle through the worksheets. Then use the Range.Find method to check if the cell is found on the worksheet. If it is, just write the sheet name to your cover sheet. You can concatenate to one cell, or use a counter to move to the next available column.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM