+ Reply to Thread
Results 1 to 21 of 21

Unique Values from multiple columns of Table

Hybrid View

  1. #1
    Forum Contributor
    Join Date
    11-24-2019
    Location
    India
    MS-Off Ver
    Ms. Office 2016
    Posts
    174

    Exclamation Unique Values from multiple columns of Table

    Hello,

    As per attached sample file, there are two sheets, sheet 1 is Basic Data and Sheet 2 is Expected Result.
    In basic data sheet, Table is given in which header is name of the subject and below it list of teachers is given. One teacher can be seen multiple times at different subjects. As it is sample file, in actual work number of teachers and subject may increase or decrease. Also name of the teacher and subject from basic table may also get replaced. It is because in future teacher or subject may get replace and new teacher and subject may get introduced.

    I want to have unique list of teachers in result sheet in given format. Also their name of the subjects will appear next to their name as per given format.

    In result sheet, In the blank cell of subject, automatic value 'Nil' will appear.

    In Basic data sheet, size of the table will increase or decrease with addition or deletion of the teacher and subject name.

    This code will work only in selected areas in result sheet as per given (separate instructions) in the sample file.

    Need VBA code for this. I have tried formulas but it is reducing performance/speed of the file.

    Thank you for Help.
    Attached Files Attached Files

  2. #2
    Forum Expert
    Join Date
    05-05-2015
    Location
    UK
    MS-Off Ver
    Microsoft Excel for Microsoft 365 MSO (Version 2402 Build 16.0.17328.20068) 64-bit
    Posts
    30,844

    Re: Unique Values from multiple columns of Table

    You will need a list of to provide Sr. Nos vs (Actual) Teacher Names OR do we assume columns B:C are manually completed in "Result Sheet" and so match "Teacher n" in "Base Sheet" with list in "Results Sheet" ?
    If that takes care of your original question, please select Thread Tools from the menu link above and mark this thread as SOLVED.

  3. #3
    Forum Contributor
    Join Date
    11-24-2019
    Location
    India
    MS-Off Ver
    Ms. Office 2016
    Posts
    174

    Re: Unique Values from multiple columns of Table

    I was thinking that code will find Name of the Teachers and will arrange them with serial number. There is no any pre-decided Sr. no. with teacher Name. Any teacher name may come to any serial number is acceptable.

  4. #4
    Forum Contributor
    Join Date
    11-24-2019
    Location
    India
    MS-Off Ver
    Ms. Office 2016
    Posts
    174

    Re: Unique Values from multiple columns of Table

    It will be more helpful to prepare Columns B:C in result sheet automatically and not manually.

  5. #5
    Forum Expert
    Join Date
    05-05-2015
    Location
    UK
    MS-Off Ver
    Microsoft Excel for Microsoft 365 MSO (Version 2402 Build 16.0.17328.20068) 64-bit
    Posts
    30,844

    Re: Unique Values from multiple columns of Table

    Sub Subjects2Teachers()
    
    Dim FoundCell As Range
    Dim LastCell As Range
    Dim FirstAddr As String, sparm As String
    Dim subjects As Range
    Dim srange As Range
    Dim lr As Long, lc As Long, c As Long, r As Long, n As Long
    Dim ws1 As Worksheet, ws2 As Worksheet
    
    Set ws1 = Sheets("Base Sheet")
    Set ws2 = Sheets("Result Sheet")
    
    With ws1
        lr = .[a2].CurrentRegion.Rows.Count
        lc = .[a2].CurrentRegion.Columns.Count
        Set srange = .Range("A2:Z" & lr)        ' List of subjects
        Call List_Teachers(lr, lc)              ' Create list of teachers
    End With
    
    For c = 1 To lc
        ws2.Cells(1, c + 3) = "Name of the Subject " & c  ' Headers for "Result Sheet"
    Next c
    
    With ws2
    
        For r = 2 To .Cells(Rows.Count, 3).End(xlUp).Row  '' Loop through list of teachers ...
        
            sparm = .Cells(r, 3)   ' Teacher
            
            '******************************************************************
            '  Find all subjects  for this teacher
            '
            
            With srange
                Set LastCell = .Cells(.Cells.Count)
            End With
            
            Set FoundCell = srange.Find(What:=sparm, after:=LastCell, Lookat:=xlWhole)
            
            If Not FoundCell Is Nothing Then
                FirstAddr = FoundCell.Address
            End If
            
            n = 3   ' Start column for subjects
            
            Do Until FoundCell Is Nothing                          ' loop until no more matches
                n = n + 1                                          ' increment column count for "Result Date"
                c = FoundCell.Column                               ' Subject column
                .Cells(r, n) = ws1.Cells(1, c)                     ' Assign Subject to this teacher
                Set FoundCell = srange.FindNext(after:=FoundCell)  ' Find next occernce of this teacher
                If FoundCell.Address = FirstAddr Then
                    Exit Do
                End If
            Loop
            '
            '******************************************************************
            '
            For c = 4 To lc + 3
                If .Cells(r, c) = "" Then Cells(r, c) = "Nil"  ' Set empty cells to "Nil"
            Next c
        
        Next r
        
    End With
    
    
    End Sub
    Sub List_Teachers(lastr, lastc)
    Dim rng As Range
    Dim r As Range
    Dim i As Integer
    Dim j As Long
    Dim n As Long
    Dim txt As String
    Dim ar As Variant
    Dim arr() As Variant
    
    Dim ws1 As Worksheet, ws2 As Worksheet
    
    Set ws1 = Sheets("Base Sheet")
    Set ws2 = Sheets("Result Sheet")
    
    With ws1
        Set rng = .Range(.Cells(2, 1), .Cells(lastr, lastc))
    End With
    n = 0
    ReDim arr(1 To 1)
    '
    '  Create unique list of teachers
    '
    With CreateObject("scripting.dictionary")
    
        For Each c In rng
            txt = c.Value
            If txt <> "" Then
                If Not .Exists(txt) Then
                    n = n + 1
                    .Add txt, n
                    ReDim Preserve arr(1 To n)
                   arr(n) = txt
                 End If
             End If
        Next c
        
    End With
        
        With ws2  ' "Result Data"
        
        .Range("B2:C100").ClearContents                                                  ' Clear Sr no. and Teacher columns
        .[C2].Resize(n) = Application.Transpose(arr)                                     ' Output list of teachres
        .Range("C2:C" & n + 1).Sort Key1:=Range("c1"), Order1:=xlAscending, Header:=xlNo ' Sort ascending
        
        .[C1] = "Name of Teacher"  ' Header
        
         For i = 1 To n  ' Add Sr No. column
         .Cells(i + 1, 2) = i
         Next i
         
        End With
        
    End Sub
    Attached Files Attached Files
    Last edited by JohnTopley; 06-28-2022 at 11:19 AM.

  6. #6
    Forum Contributor
    Join Date
    11-24-2019
    Location
    India
    MS-Off Ver
    Ms. Office 2016
    Posts
    174

    Re: Unique Values from multiple columns of Table

    Quote Originally Posted by JohnTopley View Post
    Sub Subjects2Teachers()
    
    Dim FoundCell As Range
    Dim LastCell As Range
    Dim FirstAddr As String, sparm As String
    Dim subjects As Range
    Dim srange As Range
    Dim lr As Long, lc As Long, c As Long, r As Long, n As Long
    Dim ws1 As Worksheet, ws2 As Worksheet
    
    Set ws1 = Sheets("Base Sheet")
    Set ws2 = Sheets("Result Sheet")
    
    With ws1
        lr = .[a2].CurrentRegion.Rows.Count
        lc = .[a2].CurrentRegion.Columns.Count
        Set srange = .Range("A2:Z" & lr)        ' List of subjects
        Call List_Teachers(lr, lc)              ' Create list of teachers
    End With
    
    For c = 1 To lc
        ws2.Cells(1, c + 3) = "Name of the Subject " & c  ' Headers for "Result Sheet"
    Next c
    
    With ws2
    
        For r = 2 To .Cells(Rows.Count, 3).End(xlUp).Row  '' Loop through list of teachers ...
        
            sparm = .Cells(r, 3)   ' Teacher
            
            '******************************************************************
            '  Find all subjects  for this teacher
            '
            
            With srange
                Set LastCell = .Cells(.Cells.Count)
            End With
            
            Set FoundCell = srange.Find(What:=sparm, after:=LastCell, Lookat:=xlWhole)
            
            If Not FoundCell Is Nothing Then
                FirstAddr = FoundCell.Address
            End If
            
            n = 3   ' Start column for subjects
            
            Do Until FoundCell Is Nothing                          ' loop until no more matches
                n = n + 1                                          ' increment column count for "Result Date"
                c = FoundCell.Column                               ' Subject column
                .Cells(r, n) = ws1.Cells(1, c)                     ' Assign Subject to this teacher
                Set FoundCell = srange.FindNext(after:=FoundCell)  ' Find next occernce of this teacher
                If FoundCell.Address = FirstAddr Then
                    Exit Do
                End If
            Loop
            '
            '******************************************************************
            '
            For c = 4 To lc + 3
                If .Cells(r, c) = "" Then Cells(r, c) = "Nil"  ' Set empty cells to "Nil"
            Next c
        
        Next r
        
    End With
    
    
    End Sub
    Sub List_Teachers(lastr, lastc)
    Dim rng As Range
    Dim r As Range
    Dim i As Integer
    Dim j As Long
    Dim n As Long
    Dim txt As String
    Dim ar As Variant
    Dim arr() As Variant
    
    Dim ws1 As Worksheet, ws2 As Worksheet
    
    Set ws1 = Sheets("Base Sheet")
    Set ws2 = Sheets("Result Sheet")
    
    With ws1
        Set rng = .Range(.Cells(2, 1), .Cells(lastr, lastc))
    End With
    n = 0
    ReDim arr(1 To 1)
    '
    '  Create unique list of teachers
    '
    With CreateObject("scripting.dictionary")
    
        For Each c In rng
            txt = c.Value
            If txt <> "" Then
                If Not .Exists(txt) Then
                    n = n + 1
                    .Add txt, n
                    ReDim Preserve arr(1 To n)
                   arr(n) = txt
                 End If
             End If
        Next c
        
    End With
        
        With ws2  ' "Result Data"
        
        .Range("B2:C100").ClearContents                                                  ' Clear Sr no. and Teacher columns
        .[C2].Resize(n) = Application.Transpose(arr)                                     ' Output list of teachres
        .Range("C2:C" & n + 1).Sort Key1:=Range("c1"), Order1:=xlAscending, Header:=xlNo ' Sort ascending
        
        .[C1] = "Name of Teacher"  ' Header
        
         For i = 1 To n  ' Add Sr No. column
         .Cells(i + 1, 2) = i
         Next i
         
        End With
        
    End Sub
    Hello, Thanks for reply,
    code works well and fetch information correctly, however it is found that in Result Sheet, texts and info in nearby columns get erased and additional subject columns are added.

  7. #7
    Forum Expert
    Join Date
    08-17-2007
    Location
    Poland
    Posts
    2,534

    Re: Unique Values from multiple columns of Table

    A slightly different way
    Sub AAA()
        Dim varrData    As Variant
        Dim varrHeader  As Variant
        Dim r As Long, c As Long
        Dim oDic        As Object
        Dim v           As Variant
        Dim i           As Long
    
        Set oDic = CreateObject("Scripting.Dictionary")
    
        varrData = Worksheets("Base Sheet").ListObjects(1).DataBodyRange.Value
        varrHeader = Worksheets("Base Sheet").ListObjects(1).HeaderRowRange.Value
    
        'add teachers (in Keys) and their subjects (in Items) to the Dictionary
        For c = 1 To UBound(varrData, 2)
            For r = 1 To UBound(varrData)
                If Len(varrData(r, c)) > 0 Then
                    If oDic.Exists(varrData(r, c)) Then
                        oDic(varrData(r, c)) = oDic(varrData(r, c)) & "|" & varrHeader(1, c)
                    Else
                        oDic.Add varrData(r, c), varrHeader(1, c)
                    End If
                End If
            Next r
        Next c
    
        
        With Worksheets("Result Sheet")
            'delete rows with old data (if exists)
            If Len(.Range("C7").Value) > 0 Then
                .Range(.Cells(7, "C"), .Cells(.Rows.Count, "C").End(xlUp)).EntireRow.Delete
            End If
            'insert list of teachers
            .Range("C7").Resize(oDic.Count).Value = Application.Transpose(oDic.Keys())
            'fill the range of 5 columns with "Nil"
            .Range("D7").Resize(oDic.Count, 5).Value = "Nil"
    
            'fetch the subjects of the following teachers and put them into the range
            For i = 0 To oDic.Count - 1
                v = Split(oDic.Items()(i), "|")
                .Range("D7").Offset(i).Resize(, UBound(v) + 1).Value = v
            Next i
    
            'insert Sr.No.
            With .Range("B7")
                .Value = 1
                .DataSeries Rowcol:=xlColumns, Type:=xlLinear, Date:=xlDay, _
                            Step:=1, Stop:=oDic.Count, Trend:=False
            End With
        End With
    
    End Sub
    Artik
    Attached Files Attached Files

  8. #8
    Forum Expert
    Join Date
    05-05-2015
    Location
    UK
    MS-Off Ver
    Microsoft Excel for Microsoft 365 MSO (Version 2402 Build 16.0.17328.20068) 64-bit
    Posts
    30,844

    Re: Unique Values from multiple columns of Table

    @Artik,

    As (a very old!) one who is still learning how to use Scripting Dictionary, it never occurred to me to do the concatenation approach.

    Nice one!

  9. #9
    Forum Expert
    Join Date
    08-17-2007
    Location
    Poland
    Posts
    2,534

    Re: Unique Values from multiple columns of Table

    I'm glad I could teach the old-timer something.

    Artik

  10. #10
    Forum Contributor
    Join Date
    11-24-2019
    Location
    India
    MS-Off Ver
    Ms. Office 2016
    Posts
    174

    Re: Unique Values from multiple columns of Table

    Quote Originally Posted by Artik View Post
    I'm glad I could teach the old-timer something.

    Artik
    Thanks friend for reply. Your code works smooth with speed. Just one small issue. When i add new name or update name of the teacher or subject, it gets included in between the list in result sheet. Due to this nearby data / information in other columns get erased.

  11. #11
    Forum Expert
    Join Date
    08-17-2007
    Location
    Poland
    Posts
    2,534

    Re: Unique Values from multiple columns of Table

    That's what I thought, it can't be that simple.
    Below is the corrected code.
    Sub AAA()
        Dim varrData    As Variant
        Dim varrHeader  As Variant
        Dim r As Long, c As Long
        Dim oDic        As Object
        Dim v           As Variant
        Dim i           As Long
        Dim varrOldResults As Variant
        Dim oDicOldRes  As Object
    
        Set oDic = CreateObject("Scripting.Dictionary")
    
        varrData = Worksheets("Base Sheet").ListObjects(1).DataBodyRange.Value
        varrHeader = Worksheets("Base Sheet").ListObjects(1).HeaderRowRange.Value
    
        'add teachers (in Keys) and their subjects (in Items) to the Dictionary
        For c = 1 To UBound(varrData, 2)
            For r = 1 To UBound(varrData)
                If Len(varrData(r, c)) > 0 Then
                    If oDic.Exists(varrData(r, c)) Then
                        oDic(varrData(r, c)) = oDic(varrData(r, c)) & "|" & varrHeader(1, c)
                    Else
                        oDic.Add varrData(r, c), varrHeader(1, c)
                    End If
                End If
            Next r
        Next c
    
    
        With Worksheets("Result Sheet")
            varrOldResults = .Range("C6").CurrentRegion.Value
    
            'delete rows with old data (if exists)
            If UBound(varrOldResults) > 1 Then
                .Range(.Cells(7, "C"), .Cells(.Rows.Count, "C").End(xlUp)).EntireRow.Delete
            End If
            'insert list of teachers
            .Range("C7").Resize(oDic.Count).Value = Application.Transpose(oDic.Keys())
            'fill the range of 5 columns with "Nil"
            .Range("D7").Resize(oDic.Count, 5).Value = "Nil"
    
            'fetch the subjects of the following teachers and put them into the range
            For i = 0 To oDic.Count - 1
                v = Split(oDic.Items()(i), "|")
                .Range("D7").Offset(i).Resize(, UBound(v) + 1).Value = v
            Next i
    
            'Restore old teachers' data (if existing)
            If UBound(varrOldResults) > 1 Then
                Set oDicOldRes = CreateObject("Scripting.Dictionary")
    
                For i = 2 To UBound(varrOldResults)
                    oDicOldRes.Add varrOldResults(i, 2), Join(Array(varrOldResults(i, 8), varrOldResults(i, 9), varrOldResults(i, 10)), "<!!!>")
                Next i
                
                For i = 0 To oDic.Count - 1
                  If oDicOldRes.Exists(oDic.Keys()(i)) Then
                    v = Split(oDicOldRes(oDic.Keys()(i)), "<!!!>")
                    .Range("I7").Offset(i).Resize(, UBound(v) + 1).Value = v
                  End If
                Next i
            End If
            
    
            'insert Sr.No.
            With .Range("B7")
                .Value = 1
                .DataSeries Rowcol:=xlColumns, Type:=xlLinear, Date:=xlDay, _
                            Step:=1, Stop:=oDic.Count, Trend:=False
            End With
        End With
    
    End Sub
    Artik

  12. #12
    Forum Contributor
    Join Date
    11-24-2019
    Location
    India
    MS-Off Ver
    Ms. Office 2016
    Posts
    174

    Re: Unique Values from multiple columns of Table

    Hello,
    While executing code i got errors. Screenshots of these errors are attached.

    Thank you.
    Attached Images Attached Images

  13. #13
    Forum Contributor
    Join Date
    11-24-2019
    Location
    India
    MS-Off Ver
    Ms. Office 2016
    Posts
    174

    Re: Unique Values from multiple columns of Table

    If i delete that line then again old issue take place...

  14. #14
    Forum Expert bebo021999's Avatar
    Join Date
    07-22-2011
    Location
    Vietnam
    MS-Off Ver
    Excel 2016
    Posts
    9,652

    Re: Unique Values from multiple columns of Table

    May be:
    HTML Code: 
    Attached Files Attached Files
    Quang PT

  15. #15
    Forum Contributor
    Join Date
    11-24-2019
    Location
    India
    MS-Off Ver
    Ms. Office 2016
    Posts
    174

    Re: Unique Values from multiple columns of Table

    Hello thanks,
    after code execution, values in nearby fields get deleted (except table headings). Also where subject names are blank, it do not show Nil.

  16. #16
    Forum Expert bebo021999's Avatar
    Join Date
    07-22-2011
    Location
    Vietnam
    MS-Off Ver
    Excel 2016
    Posts
    9,652

    Re: Unique Values from multiple columns of Table

    Quote Originally Posted by chintamani.avinash View Post
    Also where subject names are blank, it do not show Nil.
    No problem, i wiil change the code

    Quote Originally Posted by chintamani.avinash View Post
    after code execution, values in nearby fields get deleted (except table headings)
    Try to attach new file with 2 new sheets: before code running and after code running, display change

  17. #17
    Forum Contributor
    Join Date
    11-24-2019
    Location
    India
    MS-Off Ver
    Ms. Office 2016
    Posts
    174

    Re: Unique Values from multiple columns of Table

    Is it possible?
    1. to add new name entry at the bottom of in result sheet.
    2. In case of change / alter name, old entry will get deleted and new updated name will reflect at the bottom of result sheet.

    Thanks

  18. #18
    Forum Contributor
    Join Date
    11-24-2019
    Location
    India
    MS-Off Ver
    Ms. Office 2016
    Posts
    174

    Re: Unique Values from multiple columns of Table

    Hello
    I have attached new sample file with new sheet 'Result Sheet Before Code' and 'Result Sheet after code'.

    Result sheet in original file will exist but it will not contain any data. Data will get populated after execution of code as per shown in description in post no. 1 and also as per 'Result Sheet after Code'.


    Thanks for your help.
    Attached Files Attached Files

  19. #19
    Forum Expert bebo021999's Avatar
    Join Date
    07-22-2011
    Location
    Vietnam
    MS-Off Ver
    Excel 2016
    Posts
    9,652

    Re: Unique Values from multiple columns of Table

    Try again. Thanks for the feedback.
    Attached Files Attached Files

  20. #20
    Forum Contributor
    Join Date
    11-24-2019
    Location
    India
    MS-Off Ver
    Ms. Office 2016
    Posts
    174

    Re: Unique Values from multiple columns of Table

    Hello,
    Code works well but when put any value in other area where code is not expected to work, it converts that value into Nil. Means code is expected to run in the range B to H column and from 5th row onward. but if i run the code 1st time it given result properly, then if record any value out of the given range (where code is not expected to work), then every where 'Nil' occurs.
    Otherwise, code works truly well. Previous problem is solve in this code where if i add or alter name of the teacher then data do not get deleted.

    I am thankful for your concern.

  21. #21
    Forum Expert bebo021999's Avatar
    Join Date
    07-22-2011
    Location
    Vietnam
    MS-Off Ver
    Excel 2016
    Posts
    9,652

    Re: Unique Values from multiple columns of Table

    This is how the code works:
    The result sheet is from B5 down and accross
    1) Down: as far as unique teacher's name
    2) accross as far as subjects' count, plus last 3 columns of extra data

    First run: There's 4 subjects (from D to G) + 3 extra columns for data (H to J)
    second run: If there was more subjects added, the table will be added more columns to the right.

    The "-" sign will be added into blank cells, under subject's column.

    For your new issue, I still do not understand what it is.

    It is better try to upload worksheet again, before and after the SECOND run.

+ Reply to Thread

Thread Information

Users Browsing this Thread

There are currently 1 users browsing this thread. (0 members and 1 guests)

Similar Threads

  1. [SOLVED] Formula to get unique list of values from multiple columns in a table
    By paulma1960 in forum Excel Formulas & Functions
    Replies: 35
    Last Post: 10-31-2021, 07:31 PM
  2. Unique Values from 2 Columns of a table to an array
    By nikhilsharma30 in forum Excel Programming / VBA / Macros
    Replies: 4
    Last Post: 01-07-2020, 11:13 AM
  3. Replies: 8
    Last Post: 08-16-2019, 10:59 AM
  4. Insert blank rows above a table based on unique values in one of the columns in the table
    By carlito2002wgn in forum Excel Programming / VBA / Macros
    Replies: 6
    Last Post: 02-08-2019, 01:06 PM
  5. Insert blank rows above a table based on unique values in one of the columns in the table
    By carlito2002wgn in forum Excel Programming / VBA / Macros
    Replies: 0
    Last Post: 02-06-2019, 07:52 PM
  6. Replies: 16
    Last Post: 01-11-2012, 10:51 AM
  7. Replies: 5
    Last Post: 04-21-2011, 05:22 PM

Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts

Search Engine Friendly URLs by vBSEO 3.6.0 RC 1