I'm an intern and I've been struggling to find a solution since this monday...
I'm new to VBA and I don't clearly see how I can sum cells from a column based on some conditions..I tried multiple code but as soon as my codes didnt work I deleted them.
So what I'm trying to do is the following;
I've got a worksheet called worksheets("Amounts") in which I've got a data base.
What I've been struggling to do since this Monday :
Sum the amounts value in column Q ( "AMOUNT") Only if rows of COL A, col B, col C, col , col E, col F have equivalent cells value.
Then, I'd like to sum in col Q the amounts based on the previous condition and put the total in one single row in the place of the rows that contain common values.
Right after I'd like to delete each rows that were matching to one another to display the agregated amount with the common values. Like the following example;
My data base;
COL A
COL B
COL C
COL E
COL F
COL Q
CODE
STATUE
ATTRIBUTE
Country
Capital
AMOUNT
A1
OK
Z1
ENGLAND
LONDON
400
C1
NOK
R2
SPAIN
MADRID
50
A1
OK
Z1
ENGLAND
LONDON
300
D1
PENDING
X
CANADA
OTTAWA
10
the Output expected;
COL A
COL B
COL C
COL E
COL F
COL Q
CODE
STATUE
ATTRIBUTE
Country
Capital
AMOUNT
A1
OK
Z1
ENGLAND
LONDON
700
C1
NOK
R2
SPAIN
MADRID
50
D1
PENDING
X
CANADA
OTTAWA
10
==> So here we have only 2 rows with common value on col A, B, C, E and F. I'd like to sum the amounts of these two rows and delete these two rows to make a single one with these common values like the up-above example.
Obviously for the other rows that dont match with other rows I'd like to let them as they were.
the database in worksheets("Amount") can vary and can get more or less rows, so I will need to automatize this process.
Here is my last saved code:
Option Explicit
Sub agreg()
Dim i As Long
Dim ran1 As Range
ran1 = ThisWorkbook.Worksheets("Values").Range("A" & Worksheets("Values").Rows.Count).End(xlUp).row + 1
For Each i In ran1
If Cells(i, 1) = Range("A1", Range("A1").End(xlDown)).Value Then
cells(i,4) + range("D1",range("D1").End(xlDown)).Value
End If
Next i
End Sub ```
Please, test the next code:
Sub SumUnique5Cols()
Dim sh As Worksheet, lastRow As Long, arr, arrQ, rngDel As Range, i As Long, dict As Object
Set sh = Worksheets("Amounts")
lastRow = sh.Range("A" & sh.rows.count).End(xlUp).row 'last row based on A:A column
arr = sh.Range("A2:Q" & lastRow).Value2 'place the range in an array to make the code faster
Set dict = CreateObject("Scripting.Dictionary") 'set a dictionary to keep the unique keys combination value
For i = 1 To UBound(arr) 'iterate between the array elements
If Not dict.Exists(arr(i, 1) & arr(i, 2) & arr(i, 3) & arr(i, 5) & arr(i, 6)) Then 'if the combination key does not exist:
dict.Add arr(i, 1) & arr(i, 2) & arr(i, 3) & arr(i, 5) & arr(i, 6), arr(i, 17) 'it is created (and take the value of Q:Q cell)
Else 'if the key aleready exists, it adds the value in the key item:
dict(arr(i, 1) & arr(i, 2) & arr(i, 3) & arr(i, 5) & arr(i, 6)) = dict(arr(i, 1) & arr(i, 2) & arr(i, 3) & arr(i, 5) & arr(i, 6)) + arr(i, 17)
'range of the rows to be deleted is filled in this way:
If rngDel Is Nothing Then
Set rngDel = sh.Range("A" & i + 1) 'if the range does not exist, it is set (i + 1, because of iteration starting from the second row)
Else
Set rngDel = Union(rngDel, sh.Range("A" & i + 1)) 'if it exists, a union between the previus range and the new one is created
End If
End If
Next i
If Not rngDel Is Nothing Then rngDel.EntireRow.Delete 'if there are rows to be deleted, they are deleted
lastRow = sh.Range("A" & sh.rows.count).End(xlUp).row 'recalculate the last row (after rows deletion)
arr = sh.Range("A2:Q" & lastRow).Value2 'place the remained range in an array
ReDim arrQ(1 To UBound(arr), 1 To 1) 'ReDim the final array (to keep the summ) according to the remained rows
For i = 1 To UBound(arr)
arrQ(i, 1) = dict(arr(i, 1) & arr(i, 2) & arr(i, 3) & arr(i, 5) & arr(i, 6)) 'put in the array the corresponind dictionary key value
Next i
sh.Range("Q2").Resize(UBound(arrQ), 1).value = arrQ 'drop the array content at once
End Sub
In Power Query it would be simple:
Group by those columns
Aggregate by the Sum of Amount
Power Query is available in Windows Excel 2010+ and Office 365
To use Power Query
Select some cell in your Data Table
Data => Get&Transform => from Table/Range
When the PQ Editor opens: Home => Advanced Editor
Make note of the Table Name in Line 2
Paste the M Code below in place of what you see
Change the Table name in line 2 back to what was generated originally.
Read the comments and explore the Applied Steps to understand the algorithm
M Code
let
//Change table name in next line to actual table name in the workbook
Source = Excel.CurrentWorkbook(){[Name="Table10"]}[Content],
//set data types
//note the columns named ColumnN which will be different with your real data
#"Changed Type" = Table.TransformColumnTypes(Source,{
{"CODE", type text},
{"STATUE", type text},
{"ATTRIBUTE", type text},
{"Column1", type any},
{"Country", type text},
{"Capital", type text},
{"Column2", type any}, {"Column3", type any}, {"Column4", type any}, {"Column5", type any}, {"Column6", type any}, {"Column7", type any}, {"Column8", type any}, {"Column9", type any}, {"Column10", type any}, {"Column11", type any},
{"Amount", Int64.Type}}),
//group by columns 1,2,3,5,6
//return Sum of the Amount Column
#"Grouped Rows" = Table.Group(#"Changed Type", {"CODE", "STATUE", "ATTRIBUTE", "Country", "Capital"},
{{"Amount", each List.Sum([Amount]), type nullable number}})
in
#"Grouped Rows"
Data
Results
If you want to do it with VBA I would use ADODB to group the rows
Public Sub SumGroup()
Dim connection As Object
Set connection = CreateObject("ADODB.Connection")
connection.Open "Provider=Microsoft.Jet.OLEDB.4.0;" & _
"Data Source=" & ThisWorkbook.FullName & ";" & _
"Extended Properties=""Excel 8.0;HDR=Yes;"";"
Dim recordset As Object
Dim sSQL As String
sSQL = "SELECT Code, Statue, Attribute, Country, Capital, Sum(Amount) as SumAmount FROM [Database$] GROUP BY Code, Statue, Attribute, Country, Capital"
Set recordset = connection.Execute(sSQL)
Worksheets("Result").Range("A1").CopyFromRecordset recordset
recordset.Close
connection.Close
End Sub
The data should be in a sheet with the name Database. The result will be written to a sheet with the name Result. Both sheets should exist in the workbook before running the code.
A Pivottable would give you what you want without any coding nor in VBA or M
Related
Novice user here, so please bear with me. I am pretty decent with VLOOKUP, but that is about where my expertise ends.
Sheet1 is my active sheet which I am working on.
Sheet2 is my source data.
This sheet contains thousands of lines of client data over the span of the last 6 months.
Each client will currently have anywhere between 1 to 6 unique lines of data within the list (and growing), with the main difference for each client's line being a "date" (1 date per client each month), a "type" (i.e. Trail, Arrears) and a "$ amount".
There are a lot more column than I've mentioned above, so in my active sheet I have already used VLOOKUP to transfer the 3 main columns of data I am using, which are;
"Loan No", "Client Name", "Lender"
Duplicate rows, based on "Loan No" have also been removed. So, now each client just as 1 row.
What I am now trying to do, within each clients unique row, using the original source data, is populate the "$ amount" into a corresponding column, with a month heading, also based on the "Type" value
So basically
Within "Sheet1", look up Loan Number (cell A1) within "Sheet2"
Within "Sheet2", find the row that has both the matching "Loan Number" and matching "Date" (keeping in mind "Sheet1" only has the Month, whereas "Sheet2" has a full DD/MM/YYY)
If this row has a "Type" of "Trail" or "Arrears" (there are other Type fields I want to omit), then
Return the "Amount" to the cell the formula is entered into.
I know there may be multiple ways to do this, but I don't want to mess around with Pivots or anything like that, I also don't want to change the format of the source data. Basic formula is preferred as I am integrating some VBA functions using written formulas etc...
Any help would be greatly appreciated!
Simon
You'll need to adapt this across your worksheets but a SUMIFS should do it for you ...
This is the formula in cell K2 ...
=SUMIFS($F$2:$F$9,$A$2:$A$9,$H2,$D$2:$D$9,">=" & K$1,$D$2:$D$9,"<=" & EOMONTH(K$1,0))
Essentially, it's summing off your data with multiple criteria. You can add additional criteria as need be. The important thing to note here is the dates ...
K1 = 1/07/2021, formatted as ... mmmm ... it must be a date.
L1 = =EDATE(K1,1), formatted as ... mmmm
Make sure you fill across from K1 to N1.
To filter on the dates (i.e. using >= and <=) all fields need to be valid dates.
The dates are important, if they're not dates, then comparing dates (i.e. 1/01/2021) to the words (i.e. January) will not work.
Please, try the next code. It should be fast, using arrays and most of processing is done in memory. It returns in another sheet (shDest), I tested it to return in the next one:
Sub TransposeDataByLenderMonth()
Dim sh As Worksheet, shDest As Worksheet, lastR As Long, minD As Date, maxD As Date, arrD
Dim dict As Object, El, arr, arrFin, i As Long, k As Long, mtch, strD As String
Set sh = ActiveSheet 'use here the sheet you need
Set shDest = sh.Next 'use here the destination sheet (where the processing result to be returned)
'if next one is empty, the code can be used as it is
lastR = sh.Range("A" & sh.rows.Count).End(xlUp).row
minD = WorksheetFunction.min(sh.Range("D2:D" & lastR)) 'find first Date
maxD = WorksheetFunction.Max(sh.Range("D2:D" & lastR)) 'find last date
'create months arrays (one for months header and second to match the date):
arrD = GetMonthsIntArraysl(minD, maxD)
arr = sh.Range("A2:F" & lastR).Value 'place the whole range in an array, for faster iteration
'Extract unique keys by LoanNo:
Set dict = CreateObject("Scripting.Dictionary")
For i = 1 To UBound(arr)
dict(arr(i, 1)) = Empty
Next i
ReDim arrFin(1 To dict.Count + 1, 1 To UBound(arrD(1)) + 4): k = 1
'Place the header in the final array:
arrFin(1, 1) = "LoanNo": arrFin(1, 2) = "Client Name": arrFin(1, 3) = "Lender"
For i = 1 To UBound(arrD(0))
arrFin(1, 4 + i) = CStr(arrD(0)(i, 1))
Next i
k = 2 'reinitialize k to load values after the header
For Each El In dict.Keys 'iterate between the unique elements:
For i = 1 To UBound(arr) 'iterate between the main array rows:
If arr(i, 1) = El Then 'when a match is found:
arrFin(k, 1) = arr(i, 1): arrFin(k, 2) = arr(i, 2): arrFin(k, 3) = arr(i, 3)
strD = CStr(Format(DateSerial(Year(arr(i, 4)), month(arr(i, 4)), 1), "dd/mm/yyyy"))
mtch = Application.match(Replace(strD, ".", "/"), arrD(1), True)
arrFin(k, 4 + mtch) = arr(i, 6) + arrFin(k, 4 + mtch) 'add the value of the appropriate month
End If
Next i
k = k + 1
Next El
'Format a little and drop the processed array content:
With sh.Range("J1").Resize(1, UBound(arrFin, 2))
.NumberFormat = "#"
.BorderAround 1, xlMedium
End With
With sh.Range("J1").Resize(UBound(arrFin), UBound(arrFin, 2))
.Value = arrFin
.EntireColumn.AutoFit
.BorderAround 1, xlMedium
.Borders(xlInsideVertical).Weight = xlThin
End With
MsgBox "Job done..."
End Sub
'The following function returns an array of two arrays.
'One for header and the other for matching the date columns (in the final array)
Private Function GetMonthsIntArraysl(startDate As Date, endDate As Date) As Variant
Dim monthsNo As Long, rows As String, monthsInt, dd As Long, arrStr, arrD
monthsNo = DateDiff("m", startDate, endDate, vbMonday)
rows = month(startDate) & ":" & monthsNo + month(startDate)
arrStr = Evaluate("Text(Date(" & Year(startDate) & ",row(" & rows & "),1),""mmmm YYYY"")")
arrD = Evaluate("Text(Date(" & Year(startDate) & ",row(" & rows & "),1),""dd/mm/yyyy"")")
GetMonthsIntArraysl = Array(arrStr, arrD)
End Function
The above code adds all values for dates belonging to the same months/Client, if the case...
I took your question like a challenge, but you must learn that, in order to receive a solution, you must make some research by your own and show us a piece of code. Please, take it as a favor and next time place a better question, complying to the community rules, from the above mentioned point of view.
I have an Excel table source (extract is below):
Models are changing (adding new names, removing), so does change Week number in Columns (from Now till end of the year)
I need to restructure it so that it could look like this:
So that it could be normally used for further querying.
In each row there must be model name, for each model there should be Week number and corresponding matching Quantity taken from the table itself (on the intersection of Model X Week from original table).
I was smashing my head against the wall on how it can be realized in VBA. Couldn't restructure it with simple code.
try this code, just change the name of your sheets I used 2, the first is the source and the second is the destination, I hope help you
good Luck
Sub RestructureTable()
Const SourceSheetName = "Source", DestinationSheetName = "Restructure" 'Your sheet names
Dim nRowCounter As Double, nColumnSourceCounter As Double, nRowSourceCounter As Double
'--------
'-------Set the headers in destination sheet
Sheets(DestinationSheetName).Range("A1") = "Models" 'Replace "Models" as you need
Sheets(DestinationSheetName).Range("B1") = "Week" 'Replace "Week" as you need
Sheets(DestinationSheetName).Range("C1") = "Qty" 'Replace "Qty" as you need
'--------
'----------------------------------------------------
Sheets(SourceSheetName).Select 'Select the source sheet
Range("A2").Select ' select the first cell with data
nRowCounter = 2 ' Start in 2 cuase headers
'---------------------------------------------------
nRowSourceCounter = ThisWorkbook.Application.WorksheetFunction.CountA(Range("A:A")) 'count rows
nColumnSourceCounter = ThisWorkbook.Application.WorksheetFunction.CountA(Range("1:1")) 'count columns
For r = 2 To nRowSourceCounter
For c = 2 To nColumnSourceCounter
'Model
Sheets(DestinationSheetName).Range("A" & nRowCounter) = Sheets(SourceSheetName).Cells(r, 1)
'Header:Week
Sheets(DestinationSheetName).Range("B" & nRowCounter) = Sheets(SourceSheetName).Cells(1, c)
'Qty
Sheets(DestinationSheetName).Range("C" & nRowCounter) = Sheets(SourceSheetName).Cells(r, c)
nRowCounter = nRowCounter + 1
Next c
Next r
End Sub
You could do this with VBA but you could also do it with only a few steps using Power Query.
VBA Method
Here's code to do it with VBA, it assumes the data to restructure is in a sheet named Data and starts at A1.
In this code the restructured data is put on a new sheet but you could change that to put it on an existing sheet.
Option Explicit
Sub RestructureData()
Dim ws As Worksheet
Dim arrDataIn As Variant
Dim arrDataOut() As Variant
Dim cnt As Long
Dim idxCol As Long
Dim idxRow As Long
arrDataIn = Sheets("Data").Range("A1").CurrentRegion.Value
ReDim arrDataOut(1 To (UBound(arrDataIn, 1) - 1) * (UBound(arrDataIn, 2) - 1), 1 To 3)
For idxRow = LBound(arrDataIn, 1) + 1 To UBound(arrDataIn, 1)
For idxCol = LBound(arrDataIn, 2) + 1 To UBound(arrDataIn, 2)
cnt = cnt + 1
arrDataOut(cnt, 1) = arrDataIn(idxRow, 1)
arrDataOut(cnt, 2) = arrDataIn(1, idxCol)
arrDataOut(cnt, 3) = arrDataIn(idxRow, idxCol)
Next idxCol
Next idxRow
Set ws = Sheets.Add ' can be set to existing worksheet
ws.Range("A1:C1").Value = Array("Model", "Week", "Quantity")
ws.Range("A2").Resize(cnt, 3).Value = arrDataOut
End Sub
Power Query Method
Go to the sheet with the data, then go to the Data>Get & Transform Data tab.
Select From Table/Range, make sure all the data is selected and Does your data have headers? is ticked.
In Power Query select the Model column, right click and select Unpivot Other Columns.
Rename the Attribute column 'Week' and the value column 'Quantity' by double click each column header.
Click Close & Load to return the data to Excel.
This is the M Code those steps produce.
let
Source = Excel.CurrentWorkbook(){[Name="Table1"]}[Content],
#"Changed Type" = Table.TransformColumnTypes(Source,{{"Models", type text}, {"2021-03-29_(W13)", Int64.Type}, {"2021-04-05_(W14)", Int64.Type}, {"2021-04-12_(W15)", Int64.Type}, {"2021-04-19_(W16)", Int64.Type}, {"2021-04-26_(W17)", Int64.Type}}),
#"Unpivoted Other Columns" = Table.UnpivotOtherColumns(#"Changed Type", {"Models"}, "Attribute", "Value"),
#"Renamed Columns" = Table.RenameColumns(#"Unpivoted Other Columns",{{"Attribute", "Week"}, {"Value", "Quantity"}})
in
#"Renamed Columns"
I have the data in excel as below where combination of Column A and Column C makes a unique combination. As we can see there are duplicate rows(considering Column A & C). How can I consolidate the rows based on Column A & C and show row B as comma separated. Column A is sorted in my current sheet.
I have seen the question here which is similar but it is considering the unique values based on only 1 column.
I want the data to be represented as below. Is this possible?
Very easy with Power Query, available in Excel 2010+
In this case, all can be done from the User Interface.
Select some cell in the table
Data --> Get & Transform --> From Table/Range
Select the Parent Product and Product columns and Group By
Operation:= All Rows
Add Custom Column
Formula: =Table.Column([Grouped],"Sequence")
New Column Name: Sequence
Select the double headed arrow at the top of the Sequence Column
Extract values with comma separated
Delete the extra columns and rearrange.
M-Code
let
Source = Excel.CurrentWorkbook(){[Name="Table1"]}[Content],
#"Changed Type" = Table.TransformColumnTypes(Source,{{"Parent Product", type text}, {"Sequence", type any}, {"Product", type text}}),
#"Grouped Rows" = Table.Group(#"Changed Type", {"Parent Product", "Product"}, {{"Grouped", each _, type table [Parent Product=text, Sequence=anynonnull, Product=text]}}),
#"Added Custom" = Table.AddColumn(#"Grouped Rows", "Sequence", each Table.Column([Grouped],"Sequence")),
#"Extracted Values" = Table.TransformColumns(#"Added Custom", {"Sequence", each Text.Combine(List.Transform(_, Text.From), ","), type text}),
#"Reordered Columns" = Table.ReorderColumns(#"Extracted Values",{"Parent Product", "Sequence", "Product", "Grouped"}),
#"Removed Columns" = Table.RemoveColumns(#"Reordered Columns",{"Grouped"})
in
#"Removed Columns"
If you are after formulas, and you got Excel O365, you could try:
Formula in E2, dragged down:
=INDEX(A:A,MATCH(G2,C:C,0))
Formula in F2, dragged down:
=TEXTJOIN(",",,FILTER(B2:B9,C2:C9=G2))
Formula in G2:
=UNIQUE(C2:C9)
Though I'm pretty sure this can be done through PowerQuery avoiding formulas and VBA alltogether.
Here's VBA based approach.
Public Sub BuildConsolidatedList()
Dim srcWks As Worksheet, dstWks As Worksheet
Dim objDict As Object
Dim i As Long
Dim k
Set srcWks = ThisWorkbook.Sheets("Sheet1") '\\ Define Source Sheet Here
Set dstWks = ThisWorkbook.Sheets("Sheet2") '\\ Define Destination Sheet Here
Set objDict = CreateObject("Scripting.Dictionary")
objDict.CompareMode = vbTextCompare
For i = 2 To srcWks.Range("A" & srcWks.Rows.Count).End(xlUp).Row '\\ Loop through Source Data and build up unique entries
If objDict.Exists(srcWks.Range("A" & i).Value & "|" & srcWks.Range("C" & i).Value) Then
objDict.Item(srcWks.Range("A" & i).Value & "|" & srcWks.Range("C" & i).Value) = _
objDict.Item(srcWks.Range("A" & i).Value & "|" & srcWks.Range("C" & i).Value) & "," & srcWks.Range("B" & i).Value
Else
objDict.Add srcWks.Range("A" & i).Value & "|" & srcWks.Range("C" & i).Value, srcWks.Range("B" & i).Value
End If
Next i
i = 2 '\\ Destination sheet start row
For Each k In objDict.Keys '\\ Loop through all values in dictionary object
dstWks.Range("A" & i).Value = Split(k, "|")(0)
dstWks.Range("B" & i).Value = objDict.Item(k)
dstWks.Range("C" & i).Value = Split(k, "|")(1)
i = i + 1
Next k
End Sub
I have a sheet that looks similar to this:
So column A and column B are combined along with a number in column C. What I am trying to do is add up each value in each column (for example: add each C column for each time "Cat" appears, and "Dog" and "Grass", etc) and then find the value in columns A and B that is the highest, and return that value. So for example, in my example above, Dog would be the formula result because it's C column totals to 28. Is there a formula (or, most likely, a combination of formulas) that can accomplish this?
Thank you!
just to show, the formula would be:
=INDEX(INDEX(INDEX(A1:B12,N(IF({1},INT((ROW($1:$24)-1)/2)+1)),N(IF({1},MOD((ROW($1:$24)-1),2)+1))),N(IF({1},MODE.MULT(IF(ROW($1:$24)=MATCH(INDEX(A1:B12,N(IF({1},INT((ROW($1:$24)-1)/2)+1)),N(IF({1},MOD((ROW($1:$24)-1),2)+1))),INDEX(A1:B12,N(IF({1},INT((ROW($1:$24)-1)/2)+1)),N(IF({1},MOD((ROW($1:$24)-1),2)+1))),0),ROW($1:$24)*{1,1}))))),MATCH(MAX(SUMIFS(C:C,A:A,INDEX(INDEX(A1:B12,N(IF({1},INT((ROW($1:$24)-1)/2)+1)),N(IF({1},MOD((ROW($1:$24)-1),2)+1))),N(IF({1},MODE.MULT(IF(ROW($1:$24)=MATCH(INDEX(A1:B12,N(IF({1},INT((ROW($1:$24)-1)/2)+1)),N(IF({1},MOD((ROW($1:$24)-1),2)+1))),INDEX(A1:B12,N(IF({1},INT((ROW($1:$24)-1)/2)+1)),N(IF({1},MOD((ROW($1:$24)-1),2)+1))),0),ROW($1:$24)*{1,1}))))))+SUMIFS(C:C,B:B,INDEX(INDEX(A1:B12,N(IF({1},INT((ROW($1:$24)-1)/2)+1)),N(IF({1},MOD((ROW($1:$24)-1),2)+1))),N(IF({1},MODE.MULT(IF(ROW($1:$24)=MATCH(INDEX(A1:B12,N(IF({1},INT((ROW($1:$24)-1)/2)+1)),N(IF({1},MOD((ROW($1:$24)-1),2)+1))),INDEX(A1:B12,N(IF({1},INT((ROW($1:$24)-1)/2)+1)),N(IF({1},MOD((ROW($1:$24)-1),2)+1))),0),ROW($1:$24)*{1,1}))))))),SUMIFS(C:C,A:A,INDEX(INDEX(A1:B12,N(IF({1},INT((ROW($1:$24)-1)/2)+1)),N(IF({1},MOD((ROW($1:$24)-1),2)+1))),N(IF({1},MODE.MULT(IF(ROW($1:$24)=MATCH(INDEX(A1:B12,N(IF({1},INT((ROW($1:$24)-1)/2)+1)),N(IF({1},MOD((ROW($1:$24)-1),2)+1))),INDEX(A1:B12,N(IF({1},INT((ROW($1:$24)-1)/2)+1)),N(IF({1},MOD((ROW($1:$24)-1),2)+1))),0),ROW($1:$24)*{1,1}))))))+SUMIFS(C:C,B:B,INDEX(INDEX(A1:B12,N(IF({1},INT((ROW($1:$24)-1)/2)+1)),N(IF({1},MOD((ROW($1:$24)-1),2)+1))),N(IF({1},MODE.MULT(IF(ROW($1:$24)=MATCH(INDEX(A1:B12,N(IF({1},INT((ROW($1:$24)-1)/2)+1)),N(IF({1},MOD((ROW($1:$24)-1),2)+1))),INDEX(A1:B12,N(IF({1},INT((ROW($1:$24)-1)/2)+1)),N(IF({1},MOD((ROW($1:$24)-1),2)+1))),0),ROW($1:$24)*{1,1})))))),0))
This is an array formula and must be confirmed with Ctrl-Shift-Enter instead of Enter when exiting edit mode.
It gets a little more manageable with the new dynamic array formulas:
=INDEX(UNIQUE(INDEX(A1:B12,N(IF({1},INT(SEQUENCE(24,,0)/2)+1)),N(IF({1},MOD(SEQUENCE(24,,0),2)+1)))),MATCH(MAX(SUMIFS(C:C,A:A,UNIQUE(INDEX(A1:B12,N(IF({1},INT(SEQUENCE(24,,0)/2)+1)),N(IF({1},MOD(SEQUENCE(24,,0),2)+1)))))+SUMIFS(C:C,B:B,UNIQUE(INDEX(A1:B12,N(IF({1},INT(SEQUENCE(24,,0)/2)+1)),N(IF({1},MOD(SEQUENCE(24,,0),2)+1)))))),SUMIFS(C:C,A:A,UNIQUE(INDEX(A1:B12,N(IF({1},INT(SEQUENCE(24,,0)/2)+1)),N(IF({1},MOD(SEQUENCE(24,,0),2)+1)))))+SUMIFS(C:C,B:B,UNIQUE(INDEX(A1:B12,N(IF({1},INT(SEQUENCE(24,,0)/2)+1)),N(IF({1},MOD(SEQUENCE(24,,0),2)+1))))),0))
But we can use helper columns with the dynamic array formula.
In one cell we put:
=UNIQUE(INDEX(A1:B12,N(IF({1},INT(SEQUENCE(24,,0)/2)+1)),N(IF({1},MOD(SEQUENCE(24,,0),2)+1))))
I put it in E1, then I refer to that with the sumifs:
=SUMIFS(C:C,A:A,E1#)+SUMIFS(C:C,B:B,E1#)
I put that in F1, then use INDEX/MATCH:
=INDEX(E1#,MATCH(MAX(F1#),F1#,0))
Doing it the long way with normal formulas, one would need to copy paste the two columns one below the other and use Remove duplicate on the data tab to get a unique list:
Then use the formula in F1:
=SUMIFS(C:C,B:B,E1)+SUMIFS(C:C,A:A,E1)
And copy down the list. then use the INDEX/MATCH:
=INDEX(E:E,MATCH(MAX(F:F),F:F,0))
to return the desired value.
And just to be thorough here is why vba is better for this. Put this in a module:
Function myMatch(RngA As Range, RngB As Range, sumRng As Range)
If RngA.Cells.Count <> RngB.Cells.Count Or RngA.Cells.Count <> sumRng.Cells.Count Or RngB.Cells.Count <> sumRng.Cells.Count Then
myMatch = CVErr(xlErrValue)
Exit Function
End If
Dim arrA As Variant
arrA = RngA.Value
Dim arrB As Variant
arrB = RngB
Dim dict As Object
Set dict = CreateObject("Scripting.Dictionary")
Dim j As Long
For j = 1 To 2
Dim i As Long
For i = 1 To UBound(arrA)
Dim uRec As String
uRec = IIf(j = 1, arrA(i, 1), arrB(i, 1))
Dim smRec As Double
smRec = Application.SumIfs(sumRng, RngA, IIf(j = 1, arrA(i, 1), arrB(i, 1))) + Application.SumIfs(sumRng, RngB, IIf(j = 1, arrA(i, 1), arrB(i, 1)))
On Error Resume Next
dict.Add uRec, smRec
On Error GoTo 0
Next i
Next j
Dim mx As Double
mx = 0
Dim temp As String
temp = ""
Dim key As Variant
For Each key In dict.Keys
If dict(key) > mx Then
temp = key
mx = dict(key)
End If
Next key
myMatch = temp
End Function
Then all you need to do on the worksheet is call it as a normal function listing the three areas:
=myMatch(A1:A12,B1:B12,C1:C12)
You can also solved the case using Power Query.
Steps are:
Add your source data (which is the three column table) to the Power Query Editor;
Use Merge Columns function under the Transform tab to merge the first two columns by a delimiter, say semicolon ;;
Use Split Columns function under the Transform tab to split the merged column by the same delimiter, say semicolon ;, and make sure in the Advanced Options choose to put the results into Rows;
Use Group By function to group the last column by the Merged column and set SUM as the function;
Lastly, sort the last column Descending.
You can Close & Load the result to a new worksheet (by default).
Here are the Power Query M Codes behind the scene for your reference only. All steps are using built-in functions which are straight forward and easy to execute.
let
Source = Excel.CurrentWorkbook(){[Name="Table2"]}[Content],
#"Changed Type" = Table.TransformColumnTypes(Source,{{"Column1", type text}, {"Column2", type text}, {"Column3", Int64.Type}}),
#"Merged Columns" = Table.CombineColumns(#"Changed Type",{"Column1", "Column2"},Combiner.CombineTextByDelimiter(";", QuoteStyle.None),"Merged"),
#"Split Column by Delimiter" = Table.ExpandListColumn(Table.TransformColumns(#"Merged Columns", {{"Merged", Splitter.SplitTextByDelimiter(";", QuoteStyle.Csv), let itemType = (type nullable text) meta [Serialized.Text = true] in type {itemType}}}), "Merged"),
#"Changed Type1" = Table.TransformColumnTypes(#"Split Column by Delimiter",{{"Merged", type text}}),
#"Grouped Rows" = Table.Group(#"Changed Type1", {"Merged"}, {{"Sum", each List.Sum([Column3]), type number}}),
#"Sorted Rows" = Table.Sort(#"Grouped Rows",{{"Sum", Order.Descending}})
in
#"Sorted Rows"
Let me know if you have any questions. Cheers :)
In Excel (2016), I have some data that looks like this:
Based on a particular column, in this example the 'IPAddress' column, if there are multiple lines in the cell, separate the string into a new row and copy the remaining data into that row.
This is what I am looking for after the script or whatever completes.
I'm using the follow code from: Split cell with multiple lines into rows
Sub tes_5()
Dim cell_value As Variant
Dim counter As Integer
'Row counter
counter = 1
'Looping trough A column define max value
For i = 1 To 10
'Take cell at the time
cell_value = ThisWorkbook.ActiveSheet.Cells(i, 1).Value
'Split cell contents
Dim WrdArray() As String
WrdArray() = Split(cell_value, vbLf)
'Place values to the B column
For Each Item In WrdArray
ThisWorkbook.ActiveSheet.Cells(counter, 2).Value = Item
counter = counter + 1
Next Item
Next i
End Sub
That separates out the IPAddress column, but does not add the data for the other cells in the new row.
Text to columns doesn't work and Power Query (https://www.quora.com/Is-there-a-way-in-excel-to-bulk-split-cells-with-multiple-lines-inside-into-new-rows-without-overwriting-the-existing-data-below) doesn't work either.
Any other suggestions?
Update:
Just learned that by default, Excel puts a comma at the beginning of the delimiter field, which was causing my delimiter to not work when choosing line feed.
If you remove the leading comma, you "should" (like I did), get the desired results.
Pretty simple with Power Query
All you need to do is split the IPAddress column by the linefeed character into Rows
Split Column dialog from UI
M-Code
let
Source = Excel.CurrentWorkbook(){[Name="Table1"]}[Content],
#"Changed Type" = Table.TransformColumnTypes(Source,{{"Server Name", type text}, {"Serial Number", type text}, {"OS", type text}, {"IPAddress", type text}}),
#"Split Column by Delimiter" = Table.ExpandListColumn(Table.TransformColumns(#"Changed Type", {{"IPAddress", Splitter.SplitTextByDelimiter("#(lf)", QuoteStyle.Csv), let itemType = (type nullable text) meta [Serialized.Text = true] in type {itemType}}}), "IPAddress")
in
#"Split Column by Delimiter"
Try this, assuming your data starts in A2:
Sub x()
Dim r As Long, v As Variant
For r = Range("A" & Rows.Count).End(xlUp).Row To 2 Step -1
v = Split(Cells(r, 4), vbLf)
If UBound(v) > 0 Then
Cells(r + 1, 1).Resize(UBound(v), 4).Insert shift:=xlDown
Cells(r + 1, 1).Resize(UBound(v), 3).Value = Cells(r, 1).Resize(, 3).Value
Cells(r, 4).Resize(UBound(v) + 1).Value = Application.Transpose(v)
End If
Next r
End Sub