Names having same ID should come in one cell - excel

I have different ids for for different names in excel. Many names having the the same ids. How to get all the names having same id in one cell correspondingly. I need formula. Please help me out

Is this what you're looking for? It'd have been nicer if you had shown your progress so far, but hope to be of help like this.
Option Explicit
Sub Concatenate_Names()
Dim a As Integer
Dim i As Integer
Dim x As Integer
i = 1
x = *[number of items in your list]*
For a = 1 To *[number of unique values in a separate list]*
i = 1
Do While i <= x
'The cell references should be dependent on where your unique value list is,
'as well as where the full list is.
'"a" for the unique values, "i" for the full list - matching IDs
If Cells(a, 8).Value = Cells(i, 1).Value Then
'"a" for the unique values, "i" for the full list - appending names
Cells(a, 9).Value = Cells(a, 9).Value & Cells(i, 2).Value
End If
i = i + 1
Loop
Next
End Sub

If you want to avoid the VBA aproach, you still can use recursive functions :
Add column to store a semantic representation with key / values, in my example, the representation schema is : #Key1:Value11[;Value12...][#Key2:Value21[;Value22...]...]
The formula bellow recursively builds such a representation, the last row will contain the complete representation of pairs key / values :
=IF(IFERROR(FIND("#"&A2&":";C1);-1)=-1;C1&"#"&A2&":"&B2;IF(IFERROR(FIND("#";C1;FIND("#"&A2&":";C1)+1);-2) = -2;LEFT(C1;FIND("#";C1;FIND("#"&A2&":";C1)+1)-1)&";"&B2;LEFT(C1;FIND("#";C1;FIND("#"&A2&":";C1)+1)-1)&";"&B2&RIGHT(C1;LEN(C1)-FIND("#";C1;FIND("#";C1;FIND("#"&A2&":";C1)+1)) + 1)))
Add a second new column to retrieve values associeted to current row / key, the formula uses the last computed representation :
=IFERROR(LEFT(RIGHT(INDEX(C:C;MATCH(REPT("z";255);C:C));LEN(INDEX(C:C;MATCH(REPT("z";255);C:C)))-FIND("#"&A2;INDEX(C:C;MATCH(REPT("z";255);C:C)))-1-LEN(A2));FIND("#";RIGHT(INDEX(C:C;MATCH(REPT("z";255);C:C));LEN(INDEX(C:C;MATCH(REPT("z";255);C:C)))-FIND("#"&A2;INDEX(C:C;MATCH(REPT("z";255);C:C)))-1-LEN(A2));2)-1);RIGHT(INDEX(C:C;MATCH(REPT("z";255);C:C));LEN(INDEX(C:C;MATCH(REPT("z";255);C:C)))-FIND("#"&A2;INDEX(C:C;MATCH(REPT("z";255);C:C)))-1-LEN(A2)))
The result should look like this :
Key Value Representation Values
1 a #1:a a;e;i
2 b #1:a#2:b b;h
3 c #1:a#2:b#3:c c;j
1 e #1:a;e#2:b#3:c a;e;i
5 f #1:a;e#2:b#3:c#5:f f
6 g #1:a;e#2:b#3:c#5:f#6:g g
2 h #1:a;e#2:b;h#3:c#5:f#6:g b;h
1 i #1:a;e;i#2:b;h#3:c#5:f#6:g a;e;i
3 j #1:a;e;i#2:b;h#3:c;j#5:f#6:g c;j

Related

How to count differences between Cells

I have VBA which comparing 2 cells. Each cell can contain between 1 and 3 different parameters ant parameters are trimmed by the "," comparison is made by simple double for loop(check code). Thing what i can't figure it out is that: How to modify code and get number of unique entries, example
cell 1 [music, art, science]; cell 2 [art, music]; When i run my for loops i get 2 matches(which is fine) but how to count number of unique words in this case should be 3.
I have tried to enter this part of code but its not working well num_possible = num_possible + 1
game_tags_parts = Split(Cells(11, 2), ",")
game_tags_parts_j = Split(Cells(11, j), ",")
num_matches = 0
num_possible = 0
For m = LBound(game_tags_parts) To UBound(game_tags_parts)
num_possible = num_possible + 1
For n = LBound(game_tags_parts_j) To UBound(game_tags_parts_j)
If Trim(game_tags_parts(m)) = Trim(game_tags_parts_j(n)) Then
num_matches = num_matches + 1
End If
Next n
Next m
Actual result should be number of unique words used in those cells, in some cases i get 3 matches, example cell 1 [scifi, space, star] cell 2 [star, space, scifi] and its in total 3 matches. Modification should provide me an number 3 as number of unique words used in both cells. Or in this case where i have cell 1 [art, music, science] and cell 2 [scifi, space, star] where program gives me 0 same words and modification should give me a number 6 as unique used words.
One easy way to get a unique count is to use a Dictionary object:
game_tags_parts = Split(Cells(11, 2), ",")
game_tags_parts_j = Split(Cells(11, j), ",")
Dim myDict As Object
Set myDict = CreateObject("Scripting.Dictionary")
For Each v In game_tags_parts
If Not myDict.Exists(v) Then myDict.Add v, v
Next v
For Each v In game_tags_parts_j
If Not myDict.Exists(v) Then myDict.Add v, v
Next v
MsgBox "unique count: " & myDict.Count

How to group datas in specific condition and how to get minimum data in it

Having a problem with making a code in vba. First, there are numbers and datas on each row d and e, like number 1~14, 20~39, 48~60 and 84~98. These groups change each time(Randomly). What I want to get is a minimum value of each group. This value should be next to the rows with data. Could you help me with this one?
Rowsss = .Cells(Rows.Count, 4).End(3).Row
For i = 10 To Rowsss + 1
If .Cells(i, 4) - .Cells(i - 1, 4) = 1 Then
n = n + 1
next i
if .cells(i,4)-.cells(i-1,4)<>1 then
(I'm stuck in here)
End If
Next
I want to get results like group number and results
ex. 1/14/minimum value

How can I lookup data from one column, when the value I'm referencing changes columns?

I want to do an INDEX-MATCH-like lookup between two documents, except my MATCH's index array doesn't stay in one column.
In Vague-English: I want a value from a known column that matches another value that may be found in any column.
Refer to the image below. Let's call everything to the left of the bold vertical line on column H doc1, and the right side will be doc2.
Doc2 has a column "Find This", which will be the INDEX's array. It is compared with "ID1" from doc1 (Note that the values in "Find This" will not be in the same order as column ID1, but it's easier to undertsand this way).
The "[Result]" column in doc2 will be the value from doc1's "Want This" column from the row that matches "FIND THIS" ...However, sometimes the value from "FIND THIS" is not in the "ID1" column, and is instead in "ID2","ID3", etc.
So, I'm trying to generate Col K from Col J. This would be like pressing Ctrl+F and searching for a value in Col J, then taking the value from Col D in that row and copying it to Col K.
I made identical values from a column the same color in the other doc to make it easier to visualize where they are coming from.
Note also that in column F of doc1, the same value from doc2's "Find This" can be found after some other text.
Also note that the column headers are only there as examples, the ID columns are not actually numbered.
I would simply hard-code the correct column to search from, but I'm not in control of doc1, and I'm worried that future versions may have new "ID" columns, with other's being removed.
I'd prefer this to be a solution in the form of a formula, but VB will do.
To generate column K based on given values of column J then you could use the following:
=INDEX(doc1!$D$2:$D$14,SUMPRODUCT((doc1!$B$2:$H$14=J2)*ROW(doc1!$B$2:$H$14))-1)
Copy that formula down as far as you need to go.
It basically only returns the row of the where a matching column J is found. we then find that row in the index of your D range to get your value in K.
Proof of concept:
UPDATE:
If you are working with non unique entities n column J. That is the value on its own can be found in multiple rows and columns. Consider using the following to return the Last row where there J value is found:
=INDEX(doc1!$D$2:$D$14,AGGREGATE(14,6,(doc1!$B$2:$H$14=J2)*ROW(doc1!$B$2:$H$14),1)-1)
UPDATE 2:
And to return the first row where what you are looking in column J is found use:
=INDEX($D$2:$D$14,AGGREGATE(15,6,1/($B$2:$H$14=J2)*ROW($B$2:$H$14)-1,1))
Thanks to Scott Craner for the hint on the minimum formula.
To determine if you have UNIQUE data from column J in your range B2:H14 you can enter this array formula. In order to enter an array formula you need to press CTRL+SHFT+ENTER at the same time and not just ENTER. You will know you have done it right when you see {} around your formula in the formula bar. You cannot at the {} manually.
=IF(MAX(COUNTIF($B$2:$H$14,J2:J14))>1,"DUPLICATES","UNIQUE")
UPDATE 3
AGGREGATE - A relatively new function to me but goes back to Excel 2010. Aggregate is 19 functions rolled into 1. It would be nice if they all worked the same way but they do not. I think it is functions numbered 14 and up that will perform the same way an array formula or a CSE formula if you prefer. The nice thing is you do not need to use CSE when entering or editing them. SUMPRODUCT is another example of a regular formula that performs array formula calculations.
The meat of this explanation I believe is what is happening inside of the AGGREGATE brackets. If you click on the link you will get an idea of what the first two arguments are. The first defines which function you are using, and the second tell AGGREGATE how to deal with Errors, hidden rows, and some other nested functions. That is the relatively easy part. What I believe you want to know is what is happening with this:
(doc1!$B$2:$H$14=J2)*ROW(doc1!$B$2:$H$14)
For illustrative purpose lets reduce this formula to something a little smaller in scale that does the same thing. I'll avoid starting in A1 as that can make life a little easier when counting since it the 1st row and first column. So by placing the example range outside of it you can see some more special considerations potentially.
What I want to know is what row each of the items list in Column C occurs in column B
| B | C
3 | DOG | PLATYPUS
4 | CAT | DOG
5 | PLATYPUS |
The full formula for our mini example would be:
{=($B$3:$B$5=C2)*ROW($B$3:$B$5)}
And we are going to look at the following as an array
=INDEX($B$3:$B$5,AGGREGATE(14,6,($B$3:$B$5=C2)*ROW($B$3:$B$5),1)-2)
So the first brackets is going to be a Boolean array as you noted. Every cell that is TRUE will TRUE until its forced into a math calculation. When that happens, True becomes 1 and False becomes 0.I that formula was entered as a CSE formula and place in D2, it would break down as follows:
FALSE X 3
FALSE X 4
TRUE X 5
The 3, 4 and 5 come from ROW() returning the value of the row number that it is dealing with at the time of the array math operation. Little trick, we could have had ROW(1:3). Just need to make sure the size of the array matches! This is not matrix math is just straight across multiplication. And since the Boolean is now experiencing a math operation we are now looking at:
0 X 3 = 0
0 X 4 = 0
1 X 5 = 5
So the array of {0,0,5} gets handed back to the aggregate for more processing. The important thing to note here is that it contains ONLY 0 and the individual row numbers where we had a match. So with the first aggregate formula, formula 14 was chosen which is the LARGE function. And we also told it to ignore errors, which in this particular case does not matter. So after providing the array to the aggregate function, there was a ,1) to finish off the aggregate function. The 1 tells the aggregate function that we want the 1st larges number when the array is sorted from smallest to largest. If that number was 2 it would be the 2nd largest number and so on. So the last row or the only row that something is found on is returned. So in our small example it would be 5.
But wait that 5 was buried inside another function called Index. and in our small example that INDEX formula would be:
=INDEX($B$3:$B$5,AGGREGATE(...)-2)
Well we know that the range is only 3 rows long, so asking for the 5th row, would have excel smacking you up side the head with an error because your index number is out of range. So in comes the header row correction of -1 in the original formula or -2 for the small example and what we really see for the small example is:
=INDEX($B$3:$B$5,5-2)
=INDEX($B$3:$B$5,3)
and here is a weird bit of info, That last one does not become PLATYPUS...it becomes the cell reference to =B5 which pulls PLATYPUS. But that little nuance is a story for another time.
Now in the comments Scott essentially told me to invert for the error to get the first row. And this is important step for the aggregate and it had me running in circles for awhile. So the full equation for the first row option in our mini example is
=INDEX($B$3:$B$5,AGGREGATE(15,6,1/($B$3:$B$5=C2)*ROW($B$3:$B$5),1)-2)
And what Scott Craner was actually suggesting which Skips one math step is:
=INDEX($B$3:$B$5,AGGREGATE(15,6,ROW($B$3:$B$5)/($B$3:$B$5=C2),1)-2)
However since I only realized this after writing this all up the explanation will continue with the first of these two equations
So the important thing to note here is the change from function 14 to function 15 which is SMALL. Think of it a finding the minimum. And this time that 6 plays a huge factor along with the 1/. So our array in the middle this time equates to:
1/FALSE X 3
1/FALSE X 4
1/TRUE X 5
Which then becomes:
1/0 X 3
1/0 X 4
1/1 X 5
Which then has excel slapping you up side the head again because you are trying to divide by 0:
#div/0 X 3
#div/0 X 4
1/1 X 5
But you were smart and you protected yourself from that slap upside the head when you told AGGREGATE to ignore error when you used 6 as the second argument/reference! Therefore what is above becomes:
{5}
Since we are performing a SMALL, and we passed ,1) as the closing part of the AGGREGATE, we have essentially said give me the minimum row number or the 1st smallest number of the resulting array when sorted in ascending order.
The rest plays out the same as it did for the LARGE AGGREGATE method. The pitfall I fell into originally is I did not use the 1/ to force an error. As a result, every time I tried getting the SMALL of the array I was getting 0 from all the false results.
SUMPRODUCT works in a very similar fashion, but only works when your result array in the middle only returns 1 non zero answer. The reason being is the last step of the SUMPRODUCT function is to all the individual elements of the resulting array. So if you only have 1 non zero, you get that non zero number. If you had two rows that matched for instance 12 and 31, then the SUMPRODUCT method would return 43 which is not any of the row numbers you wanted, where as aggregate large would have told you 31 and aggregate small would have told you 12.
Something like this maybe, starting in K2 and copied down:
=IFERROR(INDEX(D:D,MAX(IFERROR(MATCH(J2,B:B,0),-1),IFERROR(MATCH(J2,E:E,0),-1),IFERROR(MATCH(J2,G:G,0),-1),IFERROR(MATCH(J2,H:H,0),-1))),"")
If you want to keep the positions of the columns for the Match variable, consider creating generic range names for each column you want to check, like "Col1", "Col2", "Col3". Create a few more range names than you think you will need and reference them to =$B:$B, =$E:$E etc. Plug all range names into Match functions inside the Max() statement as above.
When columns are added or removed from the table, adjust the range name definitions to the columns you want to check.
For example, if you set up the formula with five Matches inside the Max(), and the table changes so you only want to check three columns, point three of the range names to the same column. The Max() will only return one result and one lookup, even if the same column is matched several times.
I came up with a vba solution if I understood correctly:
Sub DisplayActiveRange()
Dim sheetToSearch As Worksheet
Set sheetToSearch = Sheet2
Dim sheetToOutput As Worksheet
Set sheetToOutput = Sheet1
Dim search As Range
Dim output As Range
Dim searchCol As String
searchCol = "J"
Dim outputCol As String
outputCol = "K"
Dim valueCol As String
valueCol = "D"
Dim r As Range
Dim currentRow As Integer
currentRow = 1
Dim maxRow As Integer
maxRow = sheetToOutput.UsedRange.Rows.Count
For currentRow = 1 To maxRow
Set search = Range("J" & currentRow)
For Each r In sheetToSearch.UsedRange
If r.Value <> "" Then
If r.Value = search.Value Then
Set output = sheetToOutput.Range(outputCol & currentRow)
output.Value = sheetToSearch.Range(valueCol & currentRow).Value
currentRow = currentRow + 1
Set search = sheetToOutput.Range(searchCol & currentRow)
End If
End If
Next
Next currentRow
End Sub
There might be better ways of doing it, but this will give you what you want. We assume headers in both "source" and "destination" sheets. You will need to adapt the "Const" declarations according to how your sheets are named. Press Control & G in Excel to bring up the VBA window and copy and paste this code into "This Workbook" under the "VBA Project" group, then select "Run" from the menu:
Option Explicit
Private Const sourceSheet = "Source"
Private Const destSheet = "Destination"
Public Sub FindColumns()
Dim rowCount As Long
Dim foundValue As String
Sheets(destSheet).Select
rowCount = 1 'Assume a header row
Do While Range("J" & rowCount + 1).value <> ""
rowCount = rowCount + 1
foundValue = FncFindText(Range("J" & rowCount).value)
Sheets(destSheet).Select
Range("K" & rowCount).value = foundValue
Loop
End Sub
Private Function FncFindText(value As String) As String
Dim rowLoop As Long
Dim colLoop As Integer
Dim found As Boolean
Dim pos As Long
Sheets(sourceSheet).Select
rowLoop = 1
colLoop = 0
Do While Range(alphaCon(colLoop + 1) & rowLoop + 1).value <> "" And found = False
rowLoop = rowLoop + 1
Do While Range(alphaCon(colLoop + 1) & rowLoop).value <> "" And found = False
colLoop = colLoop + 1
pos = InStr(Range(alphaCon(colLoop) & rowLoop).value, value)
If pos > 0 Then
FncFindText = Mid(Range(alphaCon(colLoop) & rowLoop).value, pos, Len(value))
found = True
End If
Loop
colLoop = 0
Loop
End Function
Private Function alphaCon(aNumber As Integer) As String
Dim letterArray As String
Dim iterations As Integer
letterArray = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
If aNumber <= 26 Then
alphaCon = (Mid$(letterArray, aNumber, 1))
Else
If aNumber Mod 26 = 0 Then
iterations = Int(aNumber / 26)
alphaCon = (Mid$(letterArray, iterations - 1, 1)) & (Mid$(letterArray, 26, 1))
Else
'we deliberately round down using 'Int' as anything with decimal places is not a full iteration.
iterations = Int(aNumber / 26)
alphaCon = (Mid$(letterArray, iterations, 1)) & (Mid$(letterArray, (aNumber - (26 * iterations)), 1))
End If
End If
End Function

Is there an easy way to change cell references in Excel VBA?

I recently developed a model for work and I am getting requests for adding additional features.
The problem isn't making the additions as most simply involve adding one or two additional columns. However, each time I add a column I must go through my code line by line and change every formula reference e.g. G to H, H to I, I to J etc.
Is there any way for me to automate this process without having to change each formula individually or a best practice that I can keep in mind when building my next model from scratch?
For example, let's say someone asks for an additional calculation that requires I insert a formula into column D. Currently I am going to each column (H, J, K, and L in the example below), and manually updating them to I, K, L, and M, respectively.
'Year 1 ASP formula = (Year 1 Bookings) / (Year 1 Units)
FormulaRange_ASP1 = "H23:H" & NumRows
Range(FormulaRange_ASP1).Value = "=IFERROR(G23/F23,0)"
Range(FormulaRange_ASP1).NumberFormat = "0.00"
Application.ScreenUpdating = False
'Year 2 AR Units formula = (Year 1 Units) * (Vlookup AR Retention Rate for product in column C)
FormulaRange_ARUnits2 = "J23:J" & NumRows
Range(FormulaRange_ARUnits2).Value = "=IF(E23 = 12,VLOOKUP(D23,$B$8:$F$19,4,FALSE),0) * F23 * AR_Opt_In"
Range(FormulaRange_ARUnits2).NumberFormat = "#,##0_)"
Application.ScreenUpdating = False
'Year 2 AR ASP formula = (Vlookup ASP for product in column C)
FormulaRange_AR_ASP2 = "K23:K" & NumRows
Range(FormulaRange_AR_ASP2).Value = "=IFERROR(VLOOKUP(D23,$B$8:$F$19,2,FALSE),0)"
Range(FormulaRange_AR_ASP2).NumberFormat = "0.00"
Application.ScreenUpdating = False
'Year 2 AR Bookings formula = (Year 2 Units) * (Year 2 ASP)
FormulaRange_AR_Bookings2 = "L23:L" & NumRows
Range(FormulaRange_AR_Bookings2).Value = "=J23 * K23"
Range(FormulaRange_AR_Bookings2).NumberFormat = "$#,##0_)"
Application.ScreenUpdating = False
What I usually do is add some constants to the beginning of the module (or a separate module, for bigger projects) with column number references.
Const c_Column1 As Integer = 1
Const c_Column2 As Integer = 2
So, throughout the code, you can do something like:
For i = 2 to 10
ActiveSheet.Cells(i, c_Column1).Value = i
Next i
.. and never have to worry about changing your code, only the constants.
Notice the use of Cells() instead of Range(), because it allows referencing the columns as numbers. To reference a range, you'll have to use the following sintax:
With ActiveSheet
For i = 2 to 10
.Range(.Cells(i, c_Column1), .Cells(i, c_Column2)).Value = i
Next i
End With
You can also declare the constants as String and assign them column letters instead of numbers. It may be easier to reference ranges, but you'll have to use string concatenation everywhere.
One possibility is to use relative R1C1 references.
E.g. instead of specifying a formula in H23 as:
Range(FormulaRange_ASP1).Value = "=IFERROR(G23/F23,0)"
You can specify it as:
Range(FormulaRange_ASP1).FormulaR1C1 = "=IFERROR(R[0]C[-1]/R[0]C[-2],0)"

Combination Generator yet keep in order

Wondering if anyone could help me. I'm stumped. It's been ages since I used excel....
I have 9 columns with different values in each cell, different numbers of cells per column.
I need a formula/macro to spit out all combinations of the cells and yet still remain in the exact same order of the columns.
For example
Columns:
D / 003 / 23 / 3 / 3R / C / VFX
... / 005 / 48 / 3 / 12 / .. / VDF
... / 007 / ... / 1 / ... /... / HSF
And it spits out like this:
D0032333RCVFX
D0032333RCVDF
D0032333RCHSF
D0034833RCVFX
D0034833RCVDF
and so on....
and so on.....
Presumably you will want to call this function with a "serial number" - so that you can call "the Nth combination". The problem then breaks into two parts:
Part 1: figure out, for a given "serial number", which element of each column you need. If you had the same number of elements E in each column it would be simple: it's like writing N in base E. When the number of elements in each column is different, it's a little bit trickier - something like this:
Option Base 1
Option Explicit
Function combinationNo(r As Range, serialNumber As Integer)
' find the number of entries in each column in range r
' and pick the Nth combination - where serialNumber = 0
' gives the top row
' assumes not all columns are same length
' but are filled starting with the first row
Dim ePerRow()
Dim columnIndex As Integer
Dim totalElements As Integer
Dim i, col
Dim tempString As String
ReDim ePerRow(r.Columns.Count)
totalElements = 1
i = 0
For Each col In r.Columns
i = i + 1
ePerRow(i) = Application.WorksheetFunction.CountA(col)
totalElements = totalElements * ePerRow(i)
Next
If serialNumber >= totalElements Then
combinationNo = "Serial number too large"
Exit Function
End If
tempString = ""
For i = 1 To UBound(ePerRow)
totalElements = totalElements / ePerRow(i)
columnIndex = Int(serialNumber / totalElements)
tempString = tempString & r.Cells(columnIndex + 1, i).Value
serialNumber = serialNumber - columnIndex * totalElements
Next i
combinationNo = tempString
End Function
You call this function with the range where your columns are, and a serial number (starting at 0 for "top row only"). It assumes that any blank space is at the bottom of each column. Otherwise, it will return a string that is the concatenation of combinations of values in each column, just as you described.
EDIT perhaps the following picture, which shows how this is used and what it actually does, helps. Note that the first reference (to the table of columns of different length) is an absolute reference (using the $ sign, so when you copy it from one cell to another, it keeps referring to the same range) while the second parameter is relative (so it points to 0, 1, 2, 3 etc in turn).

Resources