Consulting

Results 1 to 5 of 5

Thread: Two-column data transferred to single cell

  1. #1

    Two-column data transferred to single cell

    How do I do this? I have 2 columns of data: Column A and Column B. In Column A I have a list of items. In Column B, I have their corresponding prices. How do I sort them (based on their prices, the cheaper prices go first) and then display them in a single cell, with the following format: (Price_itemA) itemA#(Price_itemB) itemB#(Price_itemC) itemC, and so on.

    To illustrate:
    ColA ColB
    Ring 9
    Chalk 4
    Bell 11
    Hill 22

    Output:
    C1 = (4) Chalk#(9) Ring#(11) Bell#(22) Hill

    Is there an easy way to do this?

  2. #2
    VBAX Expert
    Joined
    Sep 2016
    Posts
    788
    Location
    Option Explicit
    
    Sub test()
        Dim r As Range
        Dim v
        Dim i As Long
        Dim s As String
        
        Set r = Range("a1").CurrentRegion
        
        With Worksheets.Add
            r.Copy .Range("a1")
            .Columns("a:b").Sort key1:=.Columns("b"), Header:=xlNo
            v = .Range("a1").CurrentRegion.Value
            Application.DisplayAlerts = False
            .Delete
            Application.DisplayAlerts = True
        End With
        
        For i = 1 To UBound(v)
            s = s & "(" & v(i, 2) & ") " & v(i, 1) & "#"
        Next
        r(1).Offset(, 2).Value = s
        
    End Sub

  3. #3
    wow thanks mana! Is there a way to remove the last "#" ?, e.g. (1) itemA#(2) itemB#(3) itemC and not (1) itemA#(2) itemB#(3) itemC#

  4. #4
    VBAX Expert
    Joined
    Sep 2016
    Posts
    788
    Location
    r(1).Offset(, 2).Value = Left(s, Len(s) - 1)

  5. #5
    thanks again!

Posting Permissions

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