在Excel中匹配多个值

我试图从数据表中获得一个不错的列表。 我的数据看起来像这样

HospitalCode Name SHAK Subdivision Specialty1 Specialty2 Specialty3 Specialty4 1301 Rich 5435 Copenhagen 84 65 1301 Rich 4434 Heart med 91 44 22 1301 Rich 9944 Lung med 33 99 1309 Bisp 4324 London 32 1309 Bisp 8483 GP 21 44 22 ... 

等约4000行。 我需要的是每个医院代码的输出以及特定医院中所有特殊专业的列表。 像这样的东西

 Hospital code Specialty1 Specialty2 Specialty3 ... Specialty99 1301 84 65 91 ... 33 1309 32 21 44 

如果selectSpecialty99只是为了说明,我需要所有与特定医院代码相关的专业。 我已经尝试过查找,但自然这只是给了我第一个价值。 我不明白sumproduct,但也许可以在这里使用? 所有的帮助将大大appriciated。 祝你今天愉快。

我认为VBA可能是您最好的解决scheme,因为数据透视表不会帮助您find多个列上的唯一值,例如Spec1,Spec2等。

至于VBA去,这是非常基本的循环 – 唯一棘手的一点是唯一性。 为了处理这个问题,我使用了一个Collection对象 – 这些对象可以用来获取唯一的值,因为它不会让你添加第二个“key”。

这个解决scheme也假设你的数据是按HOSPITAL_CODEsorting的(从你的例子看来)。 如果没有,请在运行此代码之前进行sorting

这是一个工作示例工作簿

 Sub makeTable() Dim rngHospId As Range Dim rngSpec As Range Dim listOfSpecs As New Collection Dim hosp As Range Dim spec As Range Dim wsOut As Worksheet 'Settings - change these for your situation Set wsData = Worksheets("Data") Set rngHospId = wsData.Range("A2:A7") ' Single column with Hosp IDs Set rngSpec = wsData.Range("B2:F7") 'All columns with Specialties 'Create new Worksheet for output Set wsOut = Worksheets.Add(After:=wsData) wsOut.Range("A1") = "Enter Headers Here ..." 'Process each row outRow = 2 'row to print to in output For i = 1 To rngHospId.Cells.Count Set hosp = rngHospId(i, 1) 'Add every specialty from the current row For Each spec In Intersect(rngSpec, hosp.EntireRow) If spec.Value <> "" Then On Error Resume Next 'Entries will only be added if unique listOfSpecs.Add spec.Value, CStr(spec.Value) On Error GoTo 0 End If Next spec 'If last row for a hospital, output the final list of specs If rngHospId(i + 1).Value <> hosp.Value Then 'Output wsOut.Cells(outRow, 1) = hosp.Value cnt = 0 'Print all elements of collection For Each entry In listOfSpecs cnt = cnt + 1 wsOut.Cells(outRow, 1 + cnt) = entry Next entry 'Clear Collection Set listOfSpecs = Nothing Set listOfSpecs = New Collection 'Move to next row outRow = outRow + 1 End If Next i End Sub 

你可以使用SUMIF来创build这个,只需要为总数创build一个新的标签。

我上传了一个基本的例子在以下链接:

这里