2015-04-23 139 views
1

我想從數據表中獲得一個不錯的列表。我的數據看起來像這樣在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 

其中Specialty99只是選擇表明,我需要連接到特定醫院代碼的所有專業。 我試過vlookup,但自然這只是給了我第一個值。我不明白sumproduct,但也許它可以在這裏使用? 所有幫助將大大appriciated。 祝您有愉快的一天。

+0

用(VBA)腳本/宏這樣做將需要相當長的一段時間/工作和複雜的算法。 – moffeltje

+0

@moffeltje是的,我也這麼認爲。我曾希望有某種擅長的編碼,可以替代執行。 –

+0

我認爲excel確實有一些工具可以用來使這個過程更快,但是你的案例非常具體。 – moffeltje

回答

1

我想VBA可能是你最好的解決方案,因爲透視表不會幫助找到獨特的價值在多個列,像Spec1,Spec2等

就VBA來說,這是非常基本的循環 - 唯一棘手的一點是唯一性。爲了處理這個問題,我使用了一個Collection對象 - 這些可以用來獲得唯一的值,因爲它不會讓你添加'key'的第二個副本。

該解決方案還假定您的數據按HOSPITAL_CODE排序(它看起來像您的示例)。如果沒有,請運行該代碼

這裏之前排序它是一個工作sample workbook

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 
+0

謝謝!正如我想要的那樣工作! –

0

你可以使用SUMIF來創建它,只需爲總數創建一個新的選項卡。

我已經上傳了一個基本的例子以下鏈接:

here

+0

我不打算這樣做,我打算。我不需要一個專業代碼的總和,而是每個醫院所擁有的各個專業代碼的清單。 –

+0

好吧,我誤解了,在這種情況下,我同意@Jon Carlstedt的評論數據透視表可能是最好的。 – Kdean571