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"
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 7 sets of 5 columns with similar data. Currently, I manually copy and paste each 5-column set below the previous set so that all 7 sets are in 5 columns. I need a macro that will turn this:
into this:
Can anyone help?
This macro works well for stacking multiple columns into just one column, but I can't get it to work for 5 columns at a time:
Sub CombineColumns()
Dim rng As Range
Dim iCol As Integer
Dim lastCell As Integer
Set rng = ActiveCell.CurrentRegion
lastCell = rng.Columns(1).Rows.Count + 1
For iCol = 2 To rng.Columns.Count
Range(Cells(1, iCol), Cells(rng.Columns(iCol).Rows.Count, iCol)).Cut
ActiveSheet.Paste Destination:=Cells(lastCell, 1)
lastCell = lastCell + rng.Columns(iCol).Rows.Count
Next iCol
End Sub
Try:
Sub test()
Dim MiMatriz As Variant
Dim FinalArray As Variant
Dim i As Long
Dim zz As Long
Dim PosSet As Long
Dim rngDestiny As Range
Set rngDestiny = Range("A14") 'Change this to top left cell of data destiny
MiMatriz = Range("A1").CurrentRegion.Value 'A1 is top left cell of complete dataset
ReDim FinalArray(1 To Range("A1").CurrentRegion.Columns.Count + 1, 1 To 5) As Variant
For zz = 1 To 5 Step 1
PosSet = 0
Do Until 1 + PosSet > UBound(FinalArray) - 1
For i = 2 To 6 Step 1
FinalArray(i + PosSet, zz) = MiMatriz(i, zz + PosSet)
Next i
PosSet = PosSet + 5
Loop
Next zz
'add headers in index 1
FinalArray(1, 1) = "Title 1"
FinalArray(1, 2) = "Title 2"
FinalArray(1, 3) = "Title 3"
FinalArray(1, 4) = "Title 4"
FinalArray(1, 5) = "Title 5"
'paste data
rngDestiny.Resize(UBound(FinalArray), 5).Value = FinalArray
Erase FinalArray, MiMatriz
End Sub
This is how it works:
You can also do this in Power Query available in Windows Excel 2010+ and Office 365
Algorithm
Demote the header row
Transpose the table
Split the table into "pages" where each "page" has the same number of rows as the desired number of columns
Transpose each subtable, removing the first row from all except the very first subtable
The first row of each subtable is the original column header, but we only want to retain the headers of the first five columns
Expand the subtables into one, and promote the first row to the Header position
To enter this code:
Select some cell in the original table
Data => Get&Transform => From Table/Range
In the Power Query Editor: Home => Advanced Editor
In that window, examine Line 2 and record the actual Table Name
Paste the M Code below into that window, replacing what is there
Edit Line 2 to reflect the actual Table Name
Examine the code, comments, and the Applied Steps window to understand what is going on.
Close and Load
M Code
let
Source = Excel.CurrentWorkbook(){[Name="Table4"]}[Content],
//Demote headers and transpose
#"Demoted Headers" = Table.DemoteHeaders(Source),
#"Transposed Table" = Table.Transpose(#"Demoted Headers"),
//split rows into tables of what will be number of columns
// pagesize argument <= number of columns "5"
#"Split into Separate Tables" = Table.FromList(
Table.Split(#"Transposed Table",5),
Splitter.SplitByNothing(),null, null, ExtraValues.Error),
//Transpose the subtables
// Except for first table, delete the first row after transposing:
// That would be the old column headers
#"Added Index" = Table.AddIndexColumn(#"Split into Separate Tables", "Index", 0, 1, Int64.Type),
#"Added Custom" = Table.AddColumn(#"Added Index", "Custom", each
if [Index] = 0 then Table.Transpose([Column1])
else Table.RemoveFirstN(Table.Transpose([Column1]))),
//Remove unneeded columns
#"Removed Columns" = Table.RemoveColumns(#"Added Custom",{"Column1", "Index"}),
//Expand the tables and promote first row to header row
#"Expanded Custom" = Table.ExpandTableColumn(#"Removed Columns", "Custom",
{"Column1", "Column2", "Column3", "Column4", "Column5"}, {"Column1", "Column2", "Column3", "Column4", "Column5"}),
#"Promoted Headers" = Table.PromoteHeaders(#"Expanded Custom", [PromoteAllScalars=true]),
//Set the types to text
#"Changed Type" = Table.TransformColumnTypes(#"Promoted Headers",
{{"Title 1", type text}, {"Title 2", type text}, {"Title 3", type text}, {"Title 4", type text}, {"Title 5", type text}})
in
#"Changed Type"
I have a dataset where contact information and names are correlated to companies that the individual has worked for. 1 individual can be associated with many companies. I want to consolidate information of the individuals but keep information on the different company names.
I have a VBA function that can remove duplicates of rows (name and contact info) and another VBA function that can merge two separate cells (company names) into 1 merged cell. The data isn't sorted by any particular field.
I would like to create a function that will remove duplicates of rows AND THEN merge the company name cells BUT ONLY FOR individuals that have duplicate rows removed (meaning that the individual is associated with more than 1 company).
Thanks for any help!
Sample of raw data format:
this is the function and result of VBA function 1:
Sub RemoveDuplicates()
'UpdatebyExtendoffice20160918
Dim xRow As Long
Dim xCol As Long
Dim xrg As Range
Dim xl As Long
On Error Resume Next
Set xrg = Application.InputBox("Select a range:", "Kutools for Excel", _
ActiveWindow.RangeSelection.AddressLocal, , , , , 8)
xRow = xrg.Rows.Count + xrg.Row - 1
xCol = xrg.Column
'MsgBox xRow & ":" & xCol
Application.ScreenUpdating = False
For xl = xRow To 2 Step -1
If Cells(xl, xCol) = Cells(xl - 1, xCol) Then
Cells(xl, xCol) = ""
End If
Next xl
Application.ScreenUpdating = True
End Sub
Function 2 is below and the module just concatenates and merges cells, but I don't know how to write a function that will only apply where the individual has had duplicate rows removed (meaning that individual is associated with multiple companies).
Sub MergeCells()
Dim xJoinRange As Range
Dim xDestination As Range
Set xJoinRange = Application.InputBox(prompt:="Highlight source cells to merge", Type:=8)
Set xDestination = Application.InputBox(prompt:="Highlight destination cell", Type:=8)
temp = ""
For Each Rng In xJoinRange
temp = temp & Rng.Value & " "
Next
xDestination.Value = temp
End Sub
I would approach this differently and use Power Query, available in Excel 2010+.
Power Query as a "Group By" method where you can select the columns you want to group by -- in your case it would be all the columns except the Company column. You can then concatentate the company column using linefeeds, and obtain the result you desire.
Data --> Get & Transform Data --> From Table/Range
Select all the columns except Company and Group By
The Operation is All Rows
Add Custom Column (to split out the company names with formula:
Table.Column([Grouped],"Company")
Select the Double-headed arrow at the top of the custom column
Extract values from list
Use the line feed for the separator #(lf)
Close and Load to
You may have to do some custom formatting for the phone number, and also set Word Wrap for the company column.
Here is the generated MCode:
let
Source = Excel.CurrentWorkbook(){[Name="Table3"]}[Content],
#"Changed Type" = Table.TransformColumnTypes(Source,{{"Email", type text}, {"Phone", Int64.Type}, {"First Name", type text}, {"Last Name", type text}, {"Company", type text}}),
#"Grouped Rows" = Table.Group(#"Changed Type", {"Email", "Phone", "First Name", "Last Name"}, {{"Grouped", each _, type table [Email=text, Phone=number, First Name=text, Last Name=text, Company=text]}}),
#"Added Custom" = Table.AddColumn(#"Grouped Rows", "Company", each Table.Column([Grouped],"Company")),
#"Extracted Values" = Table.TransformColumns(#"Added Custom", {"Company", each Text.Combine(List.Transform(_, Text.From), "#(lf)"), type text})
in
#"Extracted Values"
And here are the results:
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"
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