簡體   English   中英

在Excel中匹配多個值

[英]Matching multiple values in 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 

僅在選擇Speciality99的情況下,我需要與特定醫院代碼相關的所有專業。 我已經嘗試了vlookup,但是自然地這給了我第一個價值。 我不了解sumproduct,但也許可以在這里使用? 所有幫助將得到極大的應用。 祝你今天愉快。

我認為VBA可能是您最好的解決方案,因為數據透視表無法幫助在多個列 (例如Spec1,Spec2等)中查找唯一值。

就VBA而言,這是非常基本的循環-唯一棘手的是唯一性。 為了解決這個問題,我使用了Collection對象-這些對象可用於獲取唯一值,因為它不允許您添加第二個“鍵”副本。

該解決方案還假定您的數據按HOSPITAL_CODE排序(從您的示例中看起來像)。 如果沒有,請在運行此代碼之前對其進行排序

這是一個工作示例工作簿

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來創建,只需為總數創建一個新標簽即可。

我在以下鏈接上上傳了一個基本示例:

這里

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM