Related
I have a file excel (simplified below) with multiple rows with the same ID, the reson why i have multiple rows is because some field are different but i need only one row for each ID.
I have tried to solve this problem using transpose but it does not take into account when the ID is the same, also i have tried so create an IF in each column but it does not work.
Example:
Result:
I solved the problem using this macro:
Sub Consolidate_Rows()
Dim xRg As Range
Dim xRows As Long
Dim I As Long, J As Long, K As Long
On Error Resume Next
Set xRg = Application.InputBox("Select Range:", "Kutools For Excel", Selection.Address, , , , , 8)
Set xRg = Range(Intersect(xRg, ActiveSheet.UsedRange).Address)
If xRg Is Nothing Then Exit Sub
xRows = xRg.Rows.Count
For I = xRows To 2 Step -1
For J = 1 To I - 1
If xRg(I, 1).Value = xRg(J, 1).Value And J <> I Then
For K = 2 To xRg.Columns.Count
If xRg(J, K).Value <> "" Then
If xRg(I, K).Value = "" Then
xRg(I, K) = xRg(J, K).Value
Else
xRg(I, K) = xRg(I, K).Value & "," & xRg(J, K).Value
End If
End If
Next
xRg(J, 1).EntireRow.Delete
I = I - 1
J = J - 1
End If
Next
Next
ActiveSheet.UsedRange.Columns.AutoFit
End Sub
Please refer this, you can easily transform the data, as you are expecting using both Excel Formula as well as using Power Query
Approach Using Excel Formula --> Applicable to Excel 2021 & O365 Users
Formula used in cell A15
=UNIQUE(A2:E5)
Formula used in cell F15
=TRANSPOSE(FILTER($F$2:$F$5,A15=$A$2:$A$5))
Approach Using Power Query
Select the data and from Data Tab, Under Get & Transform Data Group, Click From Table/Range
On Clicking above you shall be prompted with Create Table window, click the check box on my table as headers and press ok
On doing above you shall be directed to power query editor
Select the first 5 columns by holding down the shift key and press Group By from Home Tab, under Transform group or From Transform tab
A new window opens as shown below, enter the new column name as All, and the Operation will All Rows press Ok
Next from Add Column Tab --> Click Custom Column and enter the below in custom column formula, and name new column name as Provincia
Table.Column([All],"Provincia")
Click on the dropdown from the Provincia column and select extract values, press Ok
Now again select the column Provincia and Click on Split Column From Home Tab, delimiter is comma, split at each occurrence of the delimiter and press ok, refer the image below
Once the column is split it shall show like below, and now remove the unwanted column All
Last but not least from Home Tab, Click Close & Load To
From Import Data Window --> Select Table, you can check Existing worksheet or New worksheet, if checking Existing worksheet then select the cell where you want to place the data
Expected Output as desired, this is one time process, and whenever you add new data just refresh the imported data, it updated within in few, you are not hardcoding anything here with just few simple steps, its done,
You can also paste this M-Language only change the Table Name as per your workbook
let
Source = Excel.CurrentWorkbook(){[Name="Table2"]}[Content],
#"Grouped Rows" = Table.Group(Source, {"ID", "Targa", "Modello", "Lordo Chiusura", "Lordo Apertura"}, {{"All", each _, type table [ID=text, Targa=text, Modello=text, Lordo Chiusura=text, Lordo Apertura=text, Provincia=text]}}),
#"Added Custom" = Table.AddColumn(#"Grouped Rows", "Provincia", each Table.Column([All],"Provincia")),
#"Extracted Values" = Table.TransformColumns(#"Added Custom", {"Provincia", each Text.Combine(List.Transform(_, Text.From), ","), type text}),
#"Split Column by Delimiter" = Table.SplitColumn(#"Extracted Values", "Provincia", Splitter.SplitTextByDelimiter(",", QuoteStyle.Csv), {"Provincia.1", "Provincia.2", "Provincia.3", "Provincia.4"}),
#"Removed Columns" = Table.RemoveColumns(#"Split Column by Delimiter",{"All"})
in
#"Removed Columns"
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 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 :)
First time here so apologies in advance if I'm asking this incorrectly.
I have a pretty good understanding of excel but I've only ever really used it for some easy to moderate formulas. I'm trying to figure out where to start with a problem I have but I'm not even sure what to search for to find the answer. From what I have been able to find - it should be achievable with either Power Query or a Excel-VBA macro?
I have maybe 400 rows of data on a sheet. I need to separate each row of data based on the values in 4 of the columns.
This is the screenshot I've made with a brief example of what I'm trying to achieve.
The top part of the screenshot is how the data is now. The bottom part is how I want the data to be modified. A new row is created for any fee thats been incurred (base fee for every row, then if they have incurred an order fee then a new row is added, if a priority fee has been incurred then a new row is added etc. If it's '0' then no new row).
If any one has any guidance on how to do this it'd be great. I'm not asking for the solution, but just some tips on what I can research or what I should be learning to accomplish something like this!
I'm in a hurry, so this code is rushed. Can come back and explain things if needed. But it gives me the output you've shown.
Option Explicit
Private Sub UnpivotColumns()
Dim sourceSheet As Worksheet
Set sourceSheet = ThisWorkbook.Worksheets("Sheet1")
Dim lastSourceRow As Long
lastSourceRow = sourceSheet.Cells(sourceSheet.Rows.Count, "A").End(xlUp).Row
Dim lastSourceColumn As Long
lastSourceColumn = sourceSheet.Cells(1, sourceSheet.Columns.Count).End(xlToLeft).Column
Dim sourceData As Range
Set sourceData = sourceSheet.Range("A2", sourceSheet.Cells(lastSourceRow, lastSourceColumn))
Dim destinationSheet As Worksheet
Set destinationSheet = ThisWorkbook.Worksheets("Sheet2")
destinationSheet.Cells.Clear
destinationSheet.Range("A1:D1").Value = Array("Name", "Description", "Currency", "Fee")
Dim destinationRowIndex As Long
destinationRowIndex = 1 ' Skip header row
Dim outputArray(1 To 4) As Variant ' Re-use same array throughout procedure
Dim sourceRowIndex As Long
For sourceRowIndex = 2 To lastSourceRow
' Base fee always needs writing (unconditionally)
outputArray(1) = sourceSheet.Cells(sourceRowIndex, "A") ' Name
outputArray(2) = "Base Fee" ' Description
outputArray(3) = "USD" ' Currency
outputArray(4) = 150 ' Fee amount
destinationRowIndex = destinationRowIndex + 1
destinationSheet.Cells(destinationRowIndex, "A").Resize(1, 4).Value = outputArray
Const FIRST_COLUMN_TO_UNPIVOT As Long = 4 ' Skip first three columns
Dim sourceColumnIndex As Long
For sourceColumnIndex = FIRST_COLUMN_TO_UNPIVOT To lastSourceColumn Step 2
outputArray(2) = sourceSheet.Cells(1, sourceColumnIndex) ' Unpivoted description
outputArray(3) = sourceSheet.Cells(sourceRowIndex, sourceColumnIndex + 1) ' Unpivoted currency
outputArray(4) = sourceSheet.Cells(sourceRowIndex, sourceColumnIndex) ' Unpivoted fee amount
' Skip amount if nil/zero
If outputArray(4) > 0 Then
destinationRowIndex = destinationRowIndex + 1
destinationSheet.Cells(destinationRowIndex, "A").Resize(1, 4).Value = outputArray
End If
Next sourceColumnIndex
Next sourceRowIndex
End Sub
The code makes some assumptions (which are true for your screenshot, but might not be true if the layout of your data changes).
Bad things about this code:
It is rigid and not very flexible/dynamic
It will be slow as it read/writes cells one at a time.
There is no referential integrity (column indexes/offsets are assumed and never actually checked/asserted). This becomes a problem if the layout/position of your data changes.
Good things about this code:
It hopefully works (for the example you've shown in your screenshot).
This is my data before the code (on Sheet1):
This is my data after the code (on Sheet2):
Also, something like this is equally possible in Power Query too (and probably in fewer lines of code too).
Assuming the column headers in your example (Name, Email, Order Date, Order Amount, Currency, Expedite Fee, Currency, Courier Fee, Currency) with the source data in named range with headers Table1, the powerquery code would be below.
let Source = Excel.CurrentWorkbook(){[Name="Table1"]}[Content],
#"Added Custom" = Table.AddColumn(Source, "Base Fee", each "USD:150"),
#"Merged Columns" = Table.CombineColumns(Table.TransformColumnTypes(#"Added Custom", {{"Order Amount", type text}}, "en-US"),{"Currency", "Order Amount"},Combiner.CombineTextByDelimiter(":", QuoteStyle.None),"Order Amount1"),
#"Merged Columns1" = Table.CombineColumns(Table.TransformColumnTypes(#"Merged Columns", {{"Expedite Fee", type text}}, "en-US"),{"Currency2", "Expedite Fee"},Combiner.CombineTextByDelimiter(":", QuoteStyle.None),"Expedite Fee1"),
#"Merged Columns2" = Table.CombineColumns(Table.TransformColumnTypes(#"Merged Columns1", {{"Courier Fee", type text}}, "en-US"),{"Currency3", "Courier Fee"},Combiner.CombineTextByDelimiter(":", QuoteStyle.None),"Courier Fee1"),
#"Removed Other Columns" = Table.SelectColumns(#"Merged Columns2",{"Name", "Order Amount1", "Expedite Fee1", "Courier Fee1","Base Fee"}),
#"Unpivoted Other Columns" = Table.UnpivotOtherColumns(#"Removed Other Columns", {"Name"}, "Description", "Value"),
#"Split Column by Delimiter" = Table.SplitColumn(#"Unpivoted Other Columns", "Value", Splitter.SplitTextByDelimiter(":", QuoteStyle.Csv), {"Currency", "Fee"}),
#"Replaced Value" = Table.ReplaceValue(#"Split Column by Delimiter","1","",Replacer.ReplaceText,{"Description"})
in #"Replaced Value"
I am using Office 365 and I am trying to get a data table from the web and import it in an Excel sheet together with the images. Here is the table which I am trying to import:
https://royaleapi.com/clan/90R9VPP9/war/analytics
http://i63.tinypic.com/2s655kx.jpg
As you can see from the table, there are images in cells representing certain statuses which contain meaningful data:
Medal = win
Cross = loss
Empty medal slot = missing in action
Empty cell = didn't participate
I click on data and select From Web, where I paste the link. Excel brings up the following, where I select Table 0 for the info I need.
http://i67.tinypic.com/2lmb4u0.jpg
After I click load, the generated table is as below. As you can see, there are no images which denote the status of the person, this method only gets the texts etc. but the cells which should have contained the images are not pulled.
http://i67.tinypic.com/n3kzz5.jpg
After searching online, I've managed to put together a code to isolate the images in another query (Query1) which you can find below. This query gives the images but doesn't place them in cells, I've just managed to get to the images themselves :)
let
Source = Table.FromColumns({Lines.FromBinary(Web.Contents("https://royaleapi.com/clan/8P2V9VYL/war/analytics"), null, null, 65001)}),
#"Filtered Rows" = Table.SelectRows(Source, each Text.Contains([Column1], "src=""/static/img/ui")),
#"Split Column by Delimiter" = Table.SplitColumn(#"Filtered Rows", "Column1", Splitter.SplitTextByEachDelimiter({"src=""/"}, QuoteStyle.None, true), {"Column1.1", "Column1.2"}),
#"Changed Type" = Table.TransformColumnTypes(#"Split Column by Delimiter",{{"Column1.1", type text}, {"Column1.2", type text}}),
#"Split Column by Delimiter1" = Table.SplitColumn(#"Changed Type", "Column1.2", Splitter.SplitTextByEachDelimiter({""""}, QuoteStyle.None, false), {"Column1.2.1", "Column1.2.2"}),
#"Changed Type1" = Table.TransformColumnTypes(#"Split Column by Delimiter1",{{"Column1.2.1", type text}, {"Column1.2.2", type text}}),
#"Removed Columns" = Table.RemoveColumns(#"Changed Type1",{"Column1.1", "Column1.2.2"}),
#"Added Custom" = Table.AddColumn(#"Removed Columns", "https", each "https://royaleapi.com/"),
#"Reordered Columns" = Table.ReorderColumns(#"Added Custom",{"https", "Column1.2.1"}),
#"Merged Columns" = Table.CombineColumns(#"Reordered Columns",{"https", "Column1.2.1"},Combiner.CombineTextByDelimiter("", QuoteStyle.None),"Merged"),
#"Renamed Columns" = Table.RenameColumns(#"Merged Columns",{{"Merged", "Images"}}),
#"Duplicated Column" = Table.DuplicateColumn(#"Renamed Columns", "Images", "Images - Copy"),
#"Renamed Columns1" = Table.RenameColumns(#"Duplicated Column",{{"Images - Copy", "ImageURLs"}})
in
#"Renamed Columns1"
So, is there any way to simply get the correct images in their correct cells whenever I refresh the table? Unfortunately, I have very limited coding knowledge so I am open to your suggestions and assistance :)
Thanks in advance!
Oandic
This shows how you can gather the links for the images into a 2d array that can be overlaid onto your data range in the sheet as the dimensions (number of rows and number of columns) match. It means you can loop the rows and columns of the array and use them to index into your data range to have the right location to then add your image from the image URL to the cell.
You can use .Top and .Left to position. Generic outline code given at bottom. You will need to size images appropriately and space rows and columns as well.
Option Explicit
Public Sub GetTable()
Dim sResponse As String, html As New HTMLDocument
With CreateObject("MSXML2.XMLHTTP")
.Open "GET", "https://royaleapi.com/clan/90R9VPP9/war/analytics", False
.send
sResponse = StrConv(.responseBody, vbUnicode)
End With
With html
.body.innerHTML = sResponse
Dim hTable As HTMLTable
Set hTable = .getElementsByTagName("table")(0)
End With
Dim numRows As Long, numColumns As Long, r As Long, c As Long, tr As Object, td As Object
numRows = hTable.getElementsByTagName("tr").Length
numColumns = hTable.getElementsByTagName("tr")(2).getElementsByTagName("td").Length
Dim arr()
ReDim arr(1 To numRows, 1 To numColumns)
For Each tr In hTable.getElementsByTagName("tr")
r = r + 1: c = 0
For Each td In tr.getElementsByTagName("td")
c = c + 1
arr(r, c) = GetImgLink(td.outerHTML)
Next
Next
[A1].Resize(numRows, numColumns) = arr '<== Just for example to see how would map to sheet
Stop
End Sub
Public Function GetImgLink(ByVal outerHTML As String) As String
On Error GoTo Errhand
GetImgLink = "https://royaleapi.com/" & Split(Split(outerHTML, "IMG class=""ui image"" src=""about:")(1), Chr$(34))(0)
Exit Function
Errhand:
Err.Clear
GetImgLink = vbNullString
End Function
Adding images and positioning (assuming data starts in A1 otherwise add an adjustment to the row, column indices of the link array you are looping.)
With ActiveSheet.Pictures.Insert(imageURL) ' <== Change to your sheet
.Left = ActiveSheet.Cells(1,1).Left '<== row and column argument to cells will come from loop position within array. Adjust if required.
.Top = ActiveSheet.Cells(1,1).Top
.Placement = 1
End With
Sample of how links map to sheet: