Splitting and replacing delimited strings into new rows using VBA in Excel - excel

I have data in 2 columns. The data in column B is comma delimited. I need each instance to appear on a new row while retaining it's original ID from column A. I also need the data in 3 columns so Name is in B and Number in C. It appears as so:
A--------B
1--------Sam Jones, 1 hours, Chris Bacon, 2 hours
2--------John Jacob, 3 hours
3--------John Hancock, 4 hours, Brian Smith, .5 hours
I am able to get it as such using my code below:
A--------B
1--------Sam Jones, 1
1--------Chris Bacon, 2 hours
2--------John Jacob, 3 hours
3--------John Hancock, 4
3--------Brian Smith, .5 hours
I need it to be: (notice last value in string also has hours removed when added to new line)
A---------B------------------------C
1---------Sam Jones-----------1
1---------Chris Bacon----------2
2---------John Jacob-----------3
3---------John Hancock-------4
3---------Brian Smith----------.5
I have the following code started: (I can't manage to remove the "hours" from the last person in each delimited string and I can't get it into 3 columns)
Sub splitByColB()
Dim r As Range, i As Long, ar
Set r = Worksheets("Sheet1").Range("B2").End(xlDown)
Do While r.Row > 1
ar = Split(r.Value, " hours, ")
If UBound(ar) >= 0 Then r.Value = ar(0)
For i = UBound(ar) To 1 Step -1
r.EntireRow.Copy
r.Offset(1).EntireRow.Insert
r.Offset(1).Value = ar(i)
Next
Set r = r.Offset(-1)
Loop
End Sub

Something like this is what you're looking for:
Sub tgr()
Dim ws As Worksheet
Dim aData As Variant
Dim aTemp As Variant
Dim aResults(1 To 65000, 1 To 3) As Variant
Dim ResultIndex As Long
Dim i As Long, j As Long
Set ws = ActiveWorkbook.Sheets("Sheet1")
With ws.Range("B2", ws.Cells(ws.Rows.Count, "B").End(xlUp))
If .Row < 2 Then Exit Sub 'No data
aData = .Offset(, -1).Resize(, 2).Value
End With
For i = LBound(aData, 1) To UBound(aData, 1)
If Len(Trim(aData(i, 2))) = 0 Then
ResultIndex = ResultIndex + 1
aResults(ResultIndex, 1) = aData(i, 1)
Else
aTemp = Split(aData(i, 2), ",")
For j = LBound(aTemp) To UBound(aTemp) Step 2
ResultIndex = ResultIndex + 1
aResults(ResultIndex, 1) = aData(i, 1)
aResults(ResultIndex, 2) = Trim(aTemp(j))
aResults(ResultIndex, 3) = Trim(Replace(aTemp(j + 1), "hours", vbNullString, , , vbTextCompare))
Next j
End If
Next i
ws.Range("A2").Resize(ResultIndex, UBound(aResults, 2)).Value = aResults
End Sub

You can use Power Query. It is a free MS add-in in 2010, 2013 and included in 2016 where it is called Get & Transform
Split column 2 by delimiter custom --> hours,
Select the ID column and unpivot other columns
Select column 2 and split by delimiter = comma
Remove unnecessary column
Replace value "hours"
And if you add to the table, you can re-run the query
let
Source = Excel.CurrentWorkbook(){[Name="Table1"]}[Content],
#"Changed Type" = Table.TransformColumnTypes(Source,{{"ID", Int64.Type}, {"Data", type text}}),
#"Split Column by Delimiter" = Table.SplitColumn(#"Changed Type", "Data", Splitter.SplitTextByDelimiter("hours,", QuoteStyle.Csv), {"Data.1", "Data.2"}),
#"Changed Type1" = Table.TransformColumnTypes(#"Split Column by Delimiter",{{"Data.1", type text}, {"Data.2", type text}}),
#"Unpivoted Other Columns" = Table.UnpivotOtherColumns(#"Changed Type1", {"ID"}, "Attribute", "Value"),
#"Split Column by Delimiter1" = Table.SplitColumn(#"Unpivoted Other Columns", "Value", Splitter.SplitTextByDelimiter(",", QuoteStyle.Csv), {"Value.1", "Value.2"}),
#"Changed Type2" = Table.TransformColumnTypes(#"Split Column by Delimiter1",{{"Value.1", type text}, {"Value.2", type text}}),
#"Removed Columns" = Table.RemoveColumns(#"Changed Type2",{"Attribute"}),
#"Replaced Value" = Table.ReplaceValue(#"Removed Columns","hours","",Replacer.ReplaceText,{"Value.2"})
in
#"Replaced Value"

I would use a class with the name data
Option Explicit
Public Id As String
Public FullName As String
Public hours As String
and the following code
Option Explicit
Sub SplitIt()
Dim rg As Range
Dim col As New Collection
Dim dataLine As data
Set rg = Worksheets("Sheet1").Range("A1").CurrentRegion
Dim vDat As Variant
vDat = rg.Columns
Dim lDat As Variant
Dim i As Long, j As Long
For i = LBound(vDat) To UBound(vDat)
lDat = Split(vDat(i, 2), ",")
For j = LBound(lDat) To UBound(lDat) Step 2
Dim hDat As Variant
hDat = Split(Trim(lDat(j + 1)), " ")
Set dataLine = New data
dataLine.Id = vDat(i, 1)
dataLine.FullName = Trim(lDat(j))
dataLine.hours = hDat(0)
col.Add dataLine
Next j
Next i
' Print Out
For i = 1 To col.Count
Set dataLine = col(i)
rg.Cells(i, 1) = dataLine.Id
rg.Cells(i, 2) = dataLine.FullName
rg.Cells(i, 3) = dataLine.hours
Next i
End Sub

Why not split on hours to a) add a record delimiter and b) get rid of hours?
Option Explicit
Sub splitByColB()
Dim r As Long, i As Long, hrs As Variant, cms As Variant
With Worksheets("sheet1")
For r = .Cells(.Rows.Count, "B").End(xlUp).Row To 2 Step -1
hrs = Split(.Cells(r, "B").Value2 & ", ", " hours, ")
ReDim Preserve hrs(UBound(hrs) - 1)
If CBool(UBound(hrs)) Then _
.Cells(r, "A").Offset(1, 0).Resize(UBound(hrs), 1).EntireRow.Insert
For i = UBound(hrs) To LBound(hrs) Step -1
cms = Split(hrs(i), ", ")
.Cells(r, "A").Offset(i, 0) = .Cells(r, "A").Value
.Cells(r, "A").Offset(i, 1) = cms(0)
.Cells(r, "A").Offset(i, 2) = cms(1)
Next i
Next r
End With
End Sub

Related

How to parse unique records and their row index

I have a set of files, some have no suffix and some with different suffixes. I would like to segregate the file names irrespective of their suffixes and list them along with the range of their row indices in the same spreadsheet. Below is the example and my failed code. Also attached the spreadsheet snapshot. Can you please help? Any new code/logic is welcome.
Input:
Row index
Filename
1
File1
2
File2_a
3
File2_b
4
File2_c
5
File3_a
6
File3_b
Output:
Filename
Row indices range
File1
1
1
File2
2
4
File3
5
6
VBA code
Sub GetUniqueFiles()
Dim sh As Worksheet
Set sh = ThisWorkbook.Sheets("Sheet1")
lastrow = sh1.Range("A" & Rows.Count).End(xlUp).Row
SameFile = False ' Flag to compare 2 consecutive file names
i = 3: j = 3
While i <= (lastrow - 1)
name_curt = sh.Range("B" & i).Value
name_next = sh.Range("B" & i + 1).Value
file_curt = Split(name_curt, "_")(0)
file_next = Split(name_next, "_")(0)
If file_curt <> file_next Then
sh.Range("D" & j).Value = file_curt
k1 = i
sh.Range("E" & j).Value = k1
sh.Range("F" & j).Value = k2
i = i + 1: j = j + 1
ElseIf file_curt = file_next Then
SameFile = True
sh.Range("B" & j).Value = file_curt
k1 = i
While SameFile
i = i + 1
name_curt = sh.Range("B" & i).Value
name_next = sh.Range("B" & i + 1).Value
file_curt = Split(name_curt, "_")(0)
file_next = Split(name_next, "_")(0)
Wend
End If
Wend
End Sub
Try this:
Sub GetUniqueFiles()
Dim sh As Worksheet, m, indx, rw As Range, f As String
Dim r As Long
Set sh = ThisWorkbook.Sheets("Sheet1")
Set rw = sh.Range("A3:B3") 'first input row
r = 2 'start row for output
Do While Application.CountA(rw) = 2 'loop while have data
indx = rw.Cells(1).Value
f = Split(rw.Cells(2).Value, "_")(0) ' "base" file name
m = Application.Match(f, sh.Columns("D"), 0) 'see if already listed
If IsError(m) Then 'not already listed ?
sh.Cells(r, "D").Value = f 'write file name
sh.Cells(r, "E").Value = indx 'write "first seen" index
m = r
r = r + 1
End If
sh.Cells(m, "F").Value = indx 'write "last seen" index
Set rw = rw.Offset(1, 0) 'next input row
Loop
End Sub
You can solve this without VBA. Add something like this in column C:
=LEFT(B2,IFERROR(FIND("_",B2)-1,LEN(B2)+1))
It will cut the underscore and everything after it. Next step is counting the distinct values. I would go for a pivot table, but there are lots of other ways.
You can obtain your desired output using Power Query, available in Windows Excel 2010+ and Office 365 Excel
Select some cell in your original table
Data => Get&Transform => From Table/Range or From within sheet
When the PQ UI opens, navigate to Home => Advanced Editor
Make note of the Table Name in Line 2 of the code.
Replace the existing code with the M-Code below
Change the table name in line 2 of the pasted code to your "real" table name
Examine any comments, and also the Applied Steps window, to better understand the algorithm and steps
M Code
let
//Change table name in next line to actual table name in your workbook
Source = Excel.CurrentWorkbook(){[Name="Table22"]}[Content],
//split on the underscore and remove the splitted suffix
#"Split Column by Delimiter" = Table.SplitColumn(Source, "Filename",
Splitter.SplitTextByDelimiter("_", QuoteStyle.Csv), {"Filename", "Filename.2"}),
//set data types -- frequently a good idea in PQ
#"Changed Type1" = Table.TransformColumnTypes(#"Split Column by Delimiter",{
{"Filename", type text}, {"Filename.2", type text}}),
#"Removed Columns" = Table.RemoveColumns(#"Changed Type1",{"Filename.2"}),
//Group by file name and extract the lowest and highest rows
#"Grouped Rows" = Table.Group(#"Removed Columns", {"Filename"}, {
{"Start Row", each List.Min([Row index]), type number},
{"End Row", each List.Max([Row index]), type number}})
in
#"Grouped Rows"
For execution speed and resource conservation it's best to minimize interaction with the worksheet from VBA. For example the following references the worksheet precisely twice no matter how long the list of files. Don't underestimate the value of restricting worksheet interaction from VBA.
Sub GetUniqueFiles()
Dim c&, i&, a$, b$, vIn, vOut
Const FILES_IN$ = "b3"
Const FILES_OUT$ = "d3"
With Range(FILES_IN)
vIn = .Resize(.End(xlDown).Row - .Row + 1)
End With
ReDim vOut(1 To UBound(vIn), 1 To 3)
For i = 1 To UBound(vIn)
b = Split(vIn(i, 1), "_")(0)
If a <> b Then
a = b
c = c + 1
vOut(c, 1) = b
vOut(c, 2) = i
If c > 1 Then vOut(c - 1, 3) = i - 1
End If
Next
If c > 1 Then vOut(c, 3) = i - 1
Range(FILES_OUT).Resize(UBound(vIn), 3) = vOut
End Sub

VBA transposing an array with parameters

I've managed to record all changes my team has done and in order to use it further I'll need to transpose the table into format supported by our systems. I was able to transpose one row but there are hundreds in my file so my code was useless.
My input table look like this
My goal for output looks like this
I've managed to transpose the whole table from tutorial (Essential Excel), however it doesn't fit my needs.
Sub TransposeTest()
Dim wks As Worksheet, wks2 As Worksheet
Dim MyArray As Variant
Dim LastRow As Integer, LastColumn As Integer
Dim StartCells As Range
Set wks = ThisWorkbook.Sheets("Sheet1")
Set wks2 = ThisWorkbook.Sheets("Transpose")
Set StartCell = wks.Range("A2")
LastRow = wks.Cells(wks.Rows.Count, StartCell.Column).End(xlUp).row
LastColumn = wks.Cells(StartCell.row, wks.Columns.Count).End(xlToLeft).Column
MyArray = wks.Range(StartCell, wks.Cells(LastRow, LastColumn)).Value2
MyArray = WorksheetFunction.Transpose(MyArray)
wks2.Range("a2", wks2.Cells(LastColumn, LastRow)).Value = MyArray
End Sub
I've been advised to use array for months and loop through each row however I unable to achieve it.
Please, try the next code. It should be very fast, even for large ranges. It uses arrays and works only in memory, the result being dropped at once:
Sub TransposeData()
Dim sh As Worksheet, shTr As Worksheet, lastR As Long, arr, arrfin, ArrH, i As Long, k As Long, j As Long
Set sh = ActiveSheet
Set shTr = sh.Next 'use here the sheet you need to return.
'if the next sheet is empty you can let the code as it is
lastR = sh.Range("A" & sh.rows.count).End(xlUp).row 'last row
arr = sh.Range("A1:Q" & lastR).value 'place the range in an array for faster iteration
ReDim arrfin(1 To UBound(arr) * 12 + 1, 1 To 7): k = 1 'redim the final array dimensions
ArrH = Split("Index,Person,Dept,Month,Sales,STMP,User", ",") 'create an array from the header strings
'place the headers in the first row of the final array:
For i = 0 To UBound(ArrH): arrfin(k, i + 1) = ArrH(i): Next: k = k + 1
'build the final array:
For i = 2 To UBound(arr)
For j = 1 To 12
arrfin(k + j - 1, 1) = arr(i, 1): arrfin(k + j - 1, 2) = arr(i, 2): arrfin(k + j - 1, 3) = arr(i, 3)
arrfin(k + j - 1, 4) = j & "." & Year(Date): arrfin(k + j - 1, 5) = arr(i, j + 3)
arrfin(k + j - 1, 6) = arr(i, 16): arrfin(k + j - 1, 7) = arr(i, 17)
Next j
k = k + j - 1 'reinitialize k variable for the next data row
Next i
'drop the final array content at once, and do some formatting:
With shTr.Range("A1").Resize(UBound(arrfin), UBound(arrfin, 2))
.value = arrfin
.rows(1).Font.Bold = True
.EntireColumn.AutoFit
For i = 7 To 9
.Borders(i).Weight = xlThin
.Borders.LineStyle = xlContinuous
Next
End With
MsgBox "Ready..."
End Sub
You can obtain your desired output using Power Query, available in Windows Excel 2010+ and Office 365 Excel
Select some cell in your original table
Data => Get&Transform => From Table/Range or From within sheet
When the PQ UI opens, navigate to Home => Advanced Editor
Make note of the Table Name in Line 2 of the code.
Replace the existing code with the M-Code below
Change the table name in line 2 of the pasted code to your "real" table name
Examine any comments, and also the Applied Steps window, to better understand the algorithm and steps
M Code
let
//Change table name in next row to the actual table name in your workbook
Source = Excel.CurrentWorkbook(){[Name="Table1"]}[Content],
//set the data types
#"Changed Type" = Table.TransformColumnTypes(Source,{
{"Index", Int64.Type}, {"Person", Int64.Type}, {"Dept", Int64.Type},
{"Jan", Int64.Type}, {"Feb", Int64.Type}, {"Mar", Int64.Type},
{"Apr", Int64.Type}, {"May", Int64.Type}, {"Jun", Int64.Type},
{"Jul", Int64.Type}, {"Aug", Int64.Type}, {"Sep", Int64.Type},
{"Oct", Int64.Type}, {"Nov", Int64.Type}, {"Dec", Int64.Type},
{"Time", type datetime}, {"User", type text}},"en-150"),
//Unpivot the Month columns
#"Unpivoted Other Columns" = Table.UnpivotOtherColumns(#"Changed Type",
{"Index", "Person", "Dept", "Time", "User"}, "Month", "Sales"),
//Transform "Month" column to "MonthNum.YearNum
//Not sure where the year should come from.
// for now will just hard code at as 2022
// but could use a different method.
mnthCol = Table.TransformColumns(#"Unpivoted Other Columns", {"Month", each
Date.ToText(Date.FromText("1-" & _ & "-2022"),"M.yyyy"),type text}),
//Reorder the columns
#"Reordered Columns" = Table.ReorderColumns(mnthCol,{"Index", "Person", "Dept", "Month", "Sales", "Time", "User"}),
//Rename the columns as per your example
rename = Table.RenameColumns(#"Reordered Columns",{
{"Time","STMP"},
{"Dept","Depr"}
})
in
rename
Original Data
Partial Results

Excel VBA - Separate data by pattern by using Split Function

I am working on a special filter to divide cell from column E24:E33 into separate cells in range F24:M33
There are pattern words by which I want to divide the data:
amount: price: price2: status: min: opt: cat: code z:
I have already tested several methods to solve this issue, but none gave me a proper results. Unfortunately I am not a VBA programmer on such a high level to write it on my own completely from scratch.
This is the code I have so far but still the data is not being correctly divided:
Sub qtest()
Dim a As Variant, b As Variant
'a = SpecialSplit("asdf:asdf asds:ert ert qwe d:sdfg") 'THIS TEST DATA WORKS FINE
a = SpecialSplit("amount:3 pc. price:2397 price2:0 EU status:In use min:1 opt:3 cat: DESTACO code z:") DOESN'T WORK FOR ONE CELL
'SpecialSplit = Sheets("T4").Range("E24" & Rows.Count).End(xlUp).Row 'ALSO DOESN't WORK FOR ENTIRE RANGE
ActiveCell.Offset(0, 1).Resize(1, UBound(a) - LBound(a) + 1).value = a
End Sub
Function SpecialSplit(Compound As String) As Variant
Dim pos1 As Long, pos2 As Long
Dim firstSplit As Variant
Dim elmts As Integer
Dim elmt As Integer
Dim oneel As String
firstSplit = Split(Compound, ":")
For elmt = LBound(firstSplit) To UBound(firstSplit) - 1
oneel = firstSplit(elmt + 1)
pos1 = InStr(oneel, " ")
pos2 = Len(oneel)
While pos1 > 0 And pos1 < Len(oneel) - 1
pos2 = pos1
pos1 = InStr(pos2 + 1, oneel, " ")
Wend
firstSplit(elmt) = firstSplit(elmt) & ":" & Left(oneel, pos2 - 1)
firstSplit(elmt + 1) = Right(oneel, Len(oneel) - pos2)
Next elmt
elmts = UBound(firstSplit) - LBound(firstSplit) ' one shorter
If elmts > 0 Then ReDim Preserve firstSplit(1 To elmts)
SpecialSplit = firstSplit
End Function
Sub SpecialSpread(FromCell As Range)
Dim splitSet As Variant
splitSet = SpecialSplit(FromCell(1).Text)
If UBound(splitSet) >= 0 Then
FromCell(1).Offset(0, 1).Resize(1, UBound(splitSet) - LBound(splitSet) + 1).value = splitSet
End If
End Sub
Sub qtest()
Dim a As Variant, b As Variant
'a = SpecialSplit("asdf:asdf asds:ert ert qwe d:sdfg") 'BY THIS PATTERN CODE WORKS
a = SpecialSplit("amount:3 pc. price:2397 price2:0 EU status:In use min:1 opt:3 cat: DESTACO code z:") ' BY THIS PATTERN CODE DOESN'T WORK
'SpecialSplit = Sheets("T4").Range("E2" & Rows.Count).End(xlUp).Row
ActiveCell.Offset(0, 1).Resize(1, UBound(a) - LBound(a) + 1).value = a
End Sub
You can do this in Power Query (available in Windows Excel 2010+ and Office 365.
This relies on the pattern words always being present and always in the same order.
In PQ we can actually split on the pattern words, so that part is easy.
If you just wanted to have the pattern words as column headers, we could stop there.
But since you want to have the pattern words precede the value in each cell, we have to Unpivot the table; create a merged column of the pattern word + : + value, then re-pivot on the Attribute column
To use it:
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
Source = Excel.CurrentWorkbook(){[Name="Table7"]}[Content],
#"Changed Type" = Table.TransformColumnTypes(Source,{{"Column1", type text}}),
//List to split on
codeList = {
"amount:",
"price:",
"price2:",
"status:",
"min:",
"opt:",
"category:",
"code z:"},
//strip off terminal colon (:) to create list of column headers
colNames = List.Transform(codeList, each Text.TrimEnd(_,":")),
//split on the code list, and name the new columns
split = Table.SplitColumn(#"Changed Type","Column1",
Splitter.SplitTextByEachDelimiter(codeList),List.Combine({{"Column1"},colNames})),
//remove the now empty column1
#"Removed Columns" = Table.RemoveColumns(split,{"Column1"}),
//could stop here if didn't have to merge the column header with the value
//To prefix each measurement with pattern word
#"Unpivoted Columns" = Table.UnpivotOtherColumns(#"Removed Columns", {}, "Attribute", "Value"),
#"Duplicated Column" = Table.DuplicateColumn(#"Unpivoted Columns", "Attribute", "Attribute - Copy"),
#"Merged Columns" = Table.CombineColumns(#"Duplicated Column",
{"Attribute", "Value"},Combiner.CombineTextByDelimiter(":", QuoteStyle.None),"Merged"),
rePivot = fnPivotAll(#"Merged Columns","Attribute - Copy","Merged")
in
rePivot
custom function
enter as blank query
rename fnPivotAll
//credit: Cam Wallace https://www.dingbatdata.com/2018/03/08/non-aggregate-pivot-with-multiple-rows-in-powerquery/
(Source as table,
ColToPivot as text,
ColForValues as text)=>
let
PivotColNames = List.Buffer(List.Distinct(Table.Column(Source,ColToPivot))),
#"Pivoted Column" = Table.Pivot(Source, PivotColNames, ColToPivot, ColForValues, each _),
TableFromRecordOfLists = (rec as record, fieldnames as list) =>
let
PartialRecord = Record.SelectFields(rec,fieldnames),
RecordToList = Record.ToList(PartialRecord),
Table = Table.FromColumns(RecordToList,fieldnames)
in
Table,
#"Added Custom" = Table.AddColumn(#"Pivoted Column", "Values", each TableFromRecordOfLists(_,PivotColNames)),
#"Removed Other Columns" = Table.RemoveColumns(#"Added Custom",PivotColNames),
#"Expanded Values" = Table.ExpandTableColumn(#"Removed Other Columns", "Values", PivotColNames)
in
#"Expanded Values"
Raw Data
Split Data
Alternative solution
Try the next function, please:
Function extractFrStr(strInit As String) As Variant
Dim arrStr, arrFin, i As Long, k As Long
Dim arr1, arr2, firstEl As String, secEl As String
arrStr = Split(strInit, ":") 'split the string by ":" character
ReDim arrFin(UBound(arrStr)) 'ReDim the final array at the same number of elements
For i = 0 To UBound(arrStr) - 1 'iterate between the array elements (except the last)
arr1 = Split(arrStr(i), " ") 'split the i element by space (" ")
arr2 = Split(arrStr(i + 1), " ") 'split the i + 1 element by space (" ")
If i = 0 Then 'for the first array element:
firstEl = arrStr(i) 'it receives the array elemen value
Else 'for the rest of array elements:
'extract firstEl (category) like first arr1 element, except the case of 'code z' which is extracted in a different way
firstEl = IIf(i = UBound(arrStr) - 1, arr1(UBound(arr1) - 1) & " " & arr1(UBound(arr1)), arr1(UBound(arr1)))
End If
'in order to remove array elements, the code transformes the one to be removed in "|||":
'it could be anything, but "|||" is difficult to suppose that it will be the text of a real element...
If arrStr(i + 1) <> "" Then arr2(UBound(arr2)) = "|||": If i = UBound(arrStr) - 2 Then arr2(UBound(arr2) - 1) = "|||"
'extract the secEl (the value) by joining the array after removed firstEl:
secEl = IIf(i = UBound(arrStr) - 1, arrStr(UBound(arrStr)), Join(Filter(arr2, "|||", False), " "))
arrFin(k) = firstEl & ":" & secEl: k = k + 1 'create the processed element of the array to keep the result
Next i
extractFrStr = arrFin
End Function
And use it to process your range, in the next way:
Sub SplitCategories()
Dim sh As Worksheet, c As Range, arr
Set sh = ActiveSheet
For Each c In sh.Range("E24:E33").cells
arr = extractFrStr(Trim(c.value))
c.Offset(0, 1).Resize(1, UBound(arr)).value = arr
Next c
End Sub
Well OK, that's mostly the code I gave you in a previous question/answer. In order to implement a split of cells in E24:E33, you just need to feed those cells to the SpecialSpread routine... all the qtest stuff is just testing routines.
So this adds a SpreadZone routine to act on that specific range:
Function SpecialSplit(Compound As String) As Variant
Dim pos1 As Long, pos2 As Long
Dim firstSplit As Variant
Dim elmts As Integer
Dim elmt As Integer
Dim oneel As String
firstSplit = Split(Compound, ":")
For elmt = LBound(firstSplit) To UBound(firstSplit) - 1
oneel = firstSplit(elmt + 1)
pos1 = InStr(oneel, " ")
pos2 = Len(oneel)
While pos1 > 0 And pos1 < Len(oneel) - 1
pos2 = pos1
pos1 = InStr(pos2 + 1, oneel, " ")
Wend
firstSplit(elmt) = firstSplit(elmt) & ":" & Left(oneel, pos2 - 1)
firstSplit(elmt + 1) = Right(oneel, Len(oneel) - pos2)
Next elmt
elmts = UBound(firstSplit) - LBound(firstSplit) ' one shorter
If elmts > 0 Then
oneel = firstSplit(UBound(firstSplit))
ReDim Preserve firstSplit(1 To elmts)
firstSplit(elmts) = firstSplit(elmts) & ":" & oneel
End If
SpecialSplit = firstSplit
End Function
Sub SpecialSpread(FromCell As Range)
Dim splitSet As Variant
splitSet = SpecialSplit(FromCell(1).Text)
If UBound(splitSet) >= 0 Then
FromCell(1).Offset(0, 1).Resize(1, UBound(splitSet) - LBound(splitSet) + 1).value = splitSet
End If
End Sub
Sub SpreadZone()
Dim ACell As Range
For Each ACell In Range("E24:E33")
Call SpecialSpread(ACell)
Next ACell
End Sub
Edit: tweaked SpecialSplit a little to improve last field & correct empty field handling

How to concatenate range of cells according to criteria

I have 2 columns in excel as below:
CutNo Data
1 A
1 B
1 C
2 A
2 B
3 A
I want to concatenate data of column data if the Cut No is the same and put it in another Column Named Concatenate and Count the number of occurrences and put it in another column as below
CutNo Data Concatenate Occurrences
1 A A & B & C 1
1 B
1 C
2 A A & B 1
2 B
3 A A 1
I use the following code
Sub Unique()
Dim Rng, Cel As Range
Dim lr As Long
Dim x As Integer
Dim str As String
lr = Sheets("Report").Cells(Rows.count, 1).End(xlUp).Row
Set Rng = Sheets("Report").Range("A2:A" & lr)
For x = 1 To Rng.count
For Each Cel In Rng.Cells
If Cel.Value = x Then
str = str & Rng.Cells(x, 1).Offset(0, 7) & ","
End If
Next Cel
Rng.Cells(x, 1).Offset(0, 10).Value = str
Next x
End Sub
I did not get the proper result I need,
Appreciate your support
Thanks, Regards
Moheb Labib
If you have Excel O365 with the FILTER function, you don't need VBA:
(Note: I have asssumed that Occurrences can be calculated by just counting the number of rows of CutNo. If you mean something else, please clarify)
C2: =IF(AND(A2<>A1,A2<>""),TEXTJOIN(" & ",TRUE,FILTER($B:$B,$A:$A=A2)),"")
D2: =IF(AND(A2<>A1,A2<>""),COUNTIF($A:$A,A2),"")
and fill down.
You can also do this using Power Query available in Excel 2010+
Select the entire range to include
*cannot auto-select since there are blank rows
In Excel 2016+ : Data --> Get & Transform --> From Table/Range
I'm not sure about the earlier versions, where you would download a free MS add-in for this functionality.
When the PQ Editor opens, select Home --> Advanced Editor and paste the M Code below into the window that opens.
Change the Table name in Line 2 to be the name of the Table generated when you opened PQ.
For explanations, examine the items in the Applied Steps window. If you float your cursor over any of the i icons, you will see the comment associated; if you double click on a gear wheel, it will open a dialog window so you can examine what was done.
Close and Load to: I select the column next to the original data, but there are other ways to do this.
M Code
let
Source = Excel.CurrentWorkbook(){[Name="Table1"]}[Content],
#"Changed Type" = Table.TransformColumnTypes(Source,{{"CutNo", Int64.Type}, {"Data", type text}}),
//make the grouping easier, else we'd have a group with the blank rows
#"Removed Blank Rows" = Table.SelectRows(#"Changed Type", each not List.IsEmpty(List.RemoveMatchingItems(Record.FieldValues(_), {"", null}))),
//Group by CutNo -- hence no need to sort
#"Grouped Rows" = Table.Group(#"Removed Blank Rows", {"CutNo"}, {{"Grouped", each _, type table [CutNo=nullable number, Data=nullable text]}}),
//add a blank row at the bottom of each grouped table (each CutNo group)
#"Added Custom" = Table.AddColumn(#"Grouped Rows", "addBlankRow", each Table.InsertRows([Grouped],
Table.RowCount([Grouped]),
{[CutNo=null, Data=null]})),
//remove unneded columns
#"Removed Columns" = Table.RemoveColumns(#"Added Custom",{"CutNo", "Grouped"}),
#"Added Custom1" = Table.AddColumn(#"Removed Columns", "Custom", each Table.Column([addBlankRow],"Data")),
//Concatenate the "Data"
#"Extracted Values" = Table.TransformColumns(#"Added Custom1", {"Custom", each Text.Combine(List.Transform(_, Text.From), " & "), type text}),
//Count the rows (subtract one since last row will be blank
#"Added Custom2" = Table.AddColumn(#"Extracted Values", "Custom.1", each Table.RowCount([addBlankRow])-1),
//Expand the Table column to put a blank row between each group of CutNo
#"Expanded addBlankRow" = Table.ExpandTableColumn(#"Added Custom2", "addBlankRow", {"CutNo"}, {"addBlankRow.CutNo"}),
//Add Index column so we can null out where there should be empty cells in the Concatenate Column
#"Added Index" = Table.AddIndexColumn(#"Expanded addBlankRow", "Index", 0, 1, Int64.Type),
#"Added Custom3" = Table.AddColumn(#"Added Index", "Concatenate", each
if [Index] = 0
then [Custom]
else if [addBlankRow.CutNo] = null
then null
else if [addBlankRow.CutNo] = #"Expanded addBlankRow"[addBlankRow.CutNo]{[Index]-1}
then null
else [Custom]),
//Blank cells in the Occurrence column if blank in the CutNo column
#"Added Custom4" = Table.AddColumn(#"Added Custom3", "Occurrences", each
if [Concatenate] = null then null
else [Custom.1]),
//Remove unneeded columns
#"Removed Columns1" = Table.RemoveColumns(#"Added Custom4",{"addBlankRow.CutNo", "Custom", "Custom.1", "Index"}),
//Remove bottom row which will be blank
#"Removed Bottom Rows" = Table.RemoveLastN(#"Removed Columns1",1)
in
#"Removed Bottom Rows"
First, your data in VBA form:
Cells.Clear
Cells(2, 1) = "1"
Cells(2, 2) = "A"
Cells(3, 1) = "1"
Cells(3, 2) = "B"
Cells(4, 1) = "1"
Cells(4, 2) = "C"
Cells(6, 1) = "2"
Cells(6, 2) = "A"
Cells(7, 1) = "2"
Cells(7, 2) = "B"
Cells(9, 1) = "3"
Cells(9, 2) = "A"
Second, your code reworked:
Dim rng As Range, Cel As Range
Dim lr As Long
Dim x As Integer, y As Integer
Dim str As String
lr = Cells(Rows.Count, 1).End(xlUp).Row
Set rng = Range("A2:A" & lr)
For x = 1 To rng.Count
str = ""
y = 0
For Each Cel In rng
If Cel.Value = x Then
str = str & rng.Cells(Cel.Row - 1, 2) & ","
If y = 0 Then y = Cel.Row - 1
End If
Next Cel
If y>0 Then rng.Cells(y, 4) = Left(str, Len(str) - 1)
Next x
Output:
Notes:
I have left 'occurrences' out as it seems vague.
Dim rng, Cel As Range should be Dim rng As Range, Cel As Range, otherwise rng is a
declared as a Variant.
Other than that, I have just trimmed bits off, and added a routine to calculate and format the data properly.
Previously, you were using Rng.Cells(x, 1), but the value of x doesn't change throughout the Cel loop, so you need to access the Cel.Row property to find out where the row in question is.
The y variable stores the first occurrence of x for display purposes.
Try the next code, please. Since you did not answer my clarification question, the code works with the assumption that occurrences means counting of each concatenated item:
Sub testConcatenateOnCriteria()
Dim sh As Worksheet, lastRow As Long, dict As New Scripting.Dictionary
Dim i As Long, count As Long, strVal As String, arr As Variant
Set sh = ActiveSheet 'use here your sheet
lastRow = sh.Range("A" & Rows.count).End(xlUp).Row
For i = 2 To lastRow
strVal = sh.Range("A" & i).Value
If sh.Range("B" & i).Value <> "" Then
If Not dict.Exists(strVal) Then
dict.Add strVal, Array(sh.Range("B" & i).Value, 1, i)
Else
dict(strVal) = Array(dict(strVal)(0) & sh.Range("B" & i).Value, dict(strVal)(1) + 1, dict(strVal)(2))
End If
End If
Next i
ReDim arr(1 To lastRow, 1 To 2)
arr(1, 1) = "Concatenate": arr(1, 2) = "Occurrences"
For i = 0 To dict.count - 1
arr(dict(dict.Keys(i))(2), 1) = dict(dict.Keys(i))(0): arr(dict(dict.Keys(i))(2), 2) = dict(dict.Keys(i))(1)
Next i
sh.Range("C1").Resize(UBound(arr), 2).Value = arr
End Sub

How to parse a row?

I need to write VBA code that:
Reads in rows in a sheet
Checks if column E has the character ";#" and parses the string on that character
Creates a new row and copies and pastes the row contents from the parsed row to the new row (both rows will have the same contents)
Renames the original column to the word that comes before ;#" and renames the copied column to the word that follows ";#"
Example with three columns:
Original row: String A;#String B;#StringC (cell 1) Complete (cell 2) 5/20/2019 (cell 3)
What I need:
Updated_Original row: String A Complete 5/20/2019
New row 1: String B Complete 5/20/2019
New row 2: String C Complete 5/20/2019
Private Sub CommandButton1_Click()
Dim SplitText
Dim WrdArray() As String, size As Integer
'iterate through all the rows in the sheet
For i = 1 To i = 2000
'take one cell at a time
cell_value = ThisWorkbook.ActiveSheet.Cells(i, 1).Value
size = WorksheetFunction.CountA(Worksheets(1).Columns(1))
'Split cell contents
WrdArray() = Split(cell_value, vbLf)
For j = LBound(WrdArray) To UBound(WrdArray)
Var = WrdArray()(0)
Next j
' WrdArray().Resize(UBound(SplitText) + 1).Value = Application.Transpose(SplitText)
ReDim WrdArray(size)
counter = counter + 1
Var = SplitText
Next i
End Sub
So long as you don't need the Title column of your screenshot in the particular order you show, this is a simple task for Power Query (aka Get & Transform in excel 2016+).
Merely
Get&Transform Data from Table/Range
Split by delimiter (and your delimiter appears to be ;# and not just #
Split into rows
And you're done:
This is the M-Code for the PQ:
let
Source = Excel.CurrentWorkbook(){[Name="Table1"]}[Content],
#"Changed Type" = Table.TransformColumnTypes(Source,{{"Status", type text}, {"Priority", type text}, {"Name", type text}, {"Date", type date}}),
#"Split Column by Delimiter" = Table.ExpandListColumn(Table.TransformColumns(#"Changed Type", {{"Name", Splitter.SplitTextByDelimiter(";#", QuoteStyle.Csv), let itemType = (type nullable text) meta [Serialized.Text = true] in type {itemType}}}), "Name"),
#"Changed Type1" = Table.TransformColumnTypes(#"Split Column by Delimiter",{{"Name", type text}})
in
#"Changed Type1"
I chose to use a combo of Len() and InStr() to figure where "complete" was in your string to figure the content to append to each part of the split. I made a few assumptions related to your columns/rows (see image below):
Option Explicit
Sub fdsa()
Dim arr As Variant, i As Long, s As Long, lr As Long, c As Long, z As String
lr = Cells(Rows.Count, 1).End(xlUp).Row
For i = 1 To lr
arr = Split(Cells(i, 1).Value, ",")
If InStr(Cells(i, 1).Value, "Complete") Then z = Right(Cells(i, 1).Value, Len(Cells(i, 1).Value) - InStr(Cells(i, 1).Value, "Complete") + 1)
c = 2
For s = LBound(arr) To UBound(arr)
If s = UBound(arr) Then z = ""
Cells(i, c).Value = arr(s) & " " & z
c = c + 1
Next s
Next i
End Sub
Here's the data I used:
Making a lot of assumptions based on what appears to be incomplete information here, but according to the information and examples provided, something like this should work for you:
Sub tgr()
Dim ws As Worksheet
Dim rData As Range
Dim aResults() As Variant
Dim aData As Variant
Dim vTemp As Variant
Dim sTemp As String
Dim ixResult As Long
Dim i As Long, j As Long
Set ws = ActiveWorkbook.ActiveSheet
Set rData = ws.Range("A1").CurrentRegion
If rData.Cells.Count = 1 Then
ReDim aData(1 To 1, 1 To 1)
aData(1, 1) = rData.Value
Else
aData = rData.Value
End If
ReDim aResults(1 To 65000, 1 To UBound(aData, 2))
ixResult = 0
For i = 1 To UBound(aData, 1)
For Each vTemp In Split(Replace(aData(i, 1), ";#", ","), ",")
If Len(Trim(vTemp)) > 0 Then
ixResult = ixResult + 1
aResults(ixResult, 1) = Trim(vTemp)
For j = 2 To UBound(aData, 2)
aResults(ixResult, j) = aData(i, j)
Next j
End If
Next vTemp
Next i
rData.Resize(ixResult).Value = aResults
End Sub

Resources