Excel VBA splitting up rows - excel

If in a cell of a table of data contains a value x > 1, I would like to copy and paste the row containing that cell "x" number of times. The rows would paste with x = 1 in the next available blank row.
TREVDAN 2
CENTRAL 3
GAL FAB 1
From this.
TREVDAN 1
TREVDAN 1
CENTRAL 1
CENTRAL 1
CENTRAL 1
GAL FAB 1
To looking something like this.

This will work for you.
Sub SpecialCopy()
'Assuming A and B columns source columns
Dim i As Long, k As Long
Dim j As Long: j = 1
For i = 1 To Cells(Cells.Rows.Count, 1).End(xlUp).Row
k = 1
Do While k <= Range("B" & i).Value
'Assuming C and D are destination columns
Range("C" & j).Value = Range("A" & i).Value
Range("D" & j).Value = 1
j = j + 1
k = k + 1
Loop
Next i
End Sub

Building off of the answer provided by #Jeanno, you can use the following if you want to paste the results directly over the top of the original table:
Sub SpecialCopy()
'Assuming A and B columns source columns
Dim i As Long, k As Long
Dim j As Long: j = 1
Dim ArrayLength As Long: ArrayLength = Application.WorksheetFunction.Sum(ActiveSheet.Range("B:B"))
ReDim MyArray(1 To ArrayLength) As String
For i = 1 To Cells(Cells.Rows.Count, 1).End(xlUp).Row
k = 1
Do While k <= Range("B" & i).Value
MyArray(j) = Range("A" & i).Value
j = j + 1
k = k + 1
Loop
Next i
For Each MyCell In Range("a1:a" & ArrayLength)
MyCell.Value = MyArray(MyCell.Row())
MyCell.Offset(0, 1).Value = 1
Next MyCell
End Sub

Related

VBA Excel Insert a row if condition

I have an Excel sheet (doc1) with 4 columns. In "A" I have people names. In "B","C" and "D", I have informations on the CV of each of these people. I would like to extract in another sheet (doc2) these informations in a specific format: For each CV information, I would like to insert a row with the name of the person in "A" and one information about his CV in "B". Basically if I have 3 informations about a person in doc1 (In B,C and D), I want to have 3 rows : In A1, A2 and A3 the name of the person, and in B1, B2 and B3 the person's infos.
I have a macro which does the exact opposite, it is basically doing a Vlookup which throws multiple results. Any idea on how to turn this around? Thanks!
Option Explicit
Sub GO()
Dim J As Long
Dim I As Integer
Dim K As Long
Dim Indice As Long
Dim Tablo
Dim Nb As Integer
Application.ScreenUpdating = False
ReDim Tablo(1 To Range("A" & Rows.Count).End(xlUp).Row - 2, 1 To 2)
Tablo(1, 1) = Range("A2")
Tablo(1, 2) = Range("B2")
Nb = 1
For J = 3 To Range("A" & Rows.Count).End(xlUp).Row
For K = 1 To UBound(Tablo)
If Range("A" & J) = Tablo(K, 1) Then
For I = 1 To UBound(Tablo, 2)
If Tablo(K, I) = "" Then
Tablo(K, I) = Range("B" & J)
Exit For
End If
Next I
If I > UBound(Tablo, 2) Then
ReDim Preserve Tablo(1 To UBound(Tablo), 1 To UBound(Tablo, 2) + 1)
Tablo(K, UBound(Tablo, 2)) = Range("B" & J)
End If
Exit For
ElseIf Tablo(K, 1) = "" Then
Nb = Nb + 1
Tablo(K, 1) = Range("A" & J)
Tablo(K, 2) = Range("B" & J)
Exit For
End If
Next K
Next J
With Sheets("doc2")
.Cells.ClearContents
.Range("A2").Resize(Nb, UBound(Tablo, 2)) = Tablo
.Range("A1") = "Name"
.Range("B1") = "C.V info 1"
.Range("B1").AutoFill .Range("B1").Resize(, UBound(Tablo, 2) - 1), xlFillSeries
End With
End Sub
try somethihng like this:
Function NeverCallAFunctionGO:
dim doc1 as worksheet, doc2 as worksheet
dim lRow as long
'set your doc1 and doc2 sheets
lRow = 1
For i = 1 to doc1.range("A1").end(xldown).row
doc2.range("A" & lRow).value = doc1.range("A" & i).value
doc2.range("B" & lRow).value = doc1.range("B" & i).value
doc2.range("B" & lRow+1).value = doc1.range("C" & i).value
doc2.rangE("B" & lRow+2).value = doc1.rangE("D" & i).value
lRow = lRow + 3
Next i

Auto fill increment number in dynamic data ranges

I am stuck in my vba code and seems I setup a loop wrong. Really appreciate for some advices! Thank you very much!!
Sub code()
Dim lastRow As Long
Dim k As Integer
Dim rowPtr As Long
lastRow = Cells(Rows.Count, 1).End(xlUp).Row
For rowPtr = 2 To lastRow
If Range("A" & rowPtr + 1) <> Range("A" & rowPtr) Then
k = 1
Range("B" & rowPtr) = k
Else
If Range("A" & rowPtr + 1) = Range("A" & rowPtr) Then
Range("B" & rowPtr) = k
End If
k = k + 1
End If
Next
End Sub
Above is my code and now my VBA result is like this:
screenshot
Column C is my ideal result of the code
Rank Reps (Repeating Values)
Adjust the values in the constants section.
Note that Range("A" & rowPtr) is the same as Cells(rowPtr, "A") or Cells(rowPtr, 1), and Range("A" & Rows.Count) is the same as Cells(Rows.Count, "A") or Cells(Rows.Count, 1).
Option Explicit
Sub rankReps()
Const FirstRow As Long = 2
Const sCol As String = "A"
Const dCol As String = "B"
Dim cOffset As Long: cOffset = Columns(dCol).Column - Columns(sCol).Column
Dim LastRow As Long: LastRow = Range(sCol & Rows.Count).End(xlUp).Row
If LastRow < FirstRow Then
MsgBox "No data", vbCritical, "No Data"
Exit Sub
End If
' Write first.
Range(sCol & FirstRow).Offset(, cOffset).Value = 1
' Write remainder.
If LastRow > FirstRow Then
Dim cCell As Range ' Current Cell
Dim r As Long ' Row Counter
Dim rk As Long: rk = 1 ' Rank Counter
For r = FirstRow + 1 To LastRow ' +1: the first is already written
Set cCell = Range(sCol & r)
If cCell.Value = cCell.Offset(-1).Value Then
rk = rk + 1
Else
rk = 1
End If
cCell.Offset(, cOffset).Value = rk
Next r
End If
End Sub
Public Sub UpdateRankings(ByVal ws As Worksheet)
' Adjust as necessary.
Const firstRow As Long = 3
Const colGroupId As Long = 1
Const colRanking As Long = 6
Dim row As Long
With ws
' First value defaults to 1.
row = firstRow
.Cells(row, colRanking).Value = 1
' Remaining rows.
row = row + 1
Do While .Cells(row, colGroupId).Value <> ""
' If group id is the same as the previous row, increment rank.
If .Cells(row, colGroupId).Value = .Cells(row - 1, colGroupId).Value Then
.Cells(row, colRanking).Value = .Cells(row - 1, colRanking).Value + 1
' If group id has changed, reset rank to 1.
Else
.Cells(row, colRanking).Value = 1
End If
' Next row.
row = row + 1
Loop
End With
End Sub
Please, try the next way:
Sub Countcode()
Dim lastRow As Long, k As Long, rowPtr As Long
lastRow = cells(rows.count, 1).End(xlUp).row
k = 1
For rowPtr = 2 To lastRow
If Range("A" & rowPtr) = Range("A" & rowPtr + 1) Then
Range("B" & rowPtr) = k: k = k + 1
Else
If Range("A" & rowPtr) = Range("A" & rowPtr - 1) Then
Range("B" & rowPtr) = k: k=1
Else
k = 1
Range("B" & rowPtr) = k
End If
End If
Next
End Sub
One approach is:
Sub numberIt2()
Dim cl As Range, equal As Integer ' equal initial value is 0
Set cl = Range("A1")
Do While cl <> ""
cl.Offset(0, 1) = equal + 1
Set cl = cl.Offset(1)
equal = IIf(cl = cl.Offset(-1), equal + 1, 0)
Loop
End Sub

How to delete a row in a sheet based on values in the 3 columns

I have to delete a row if the of the column values of Column C, Column D , Column E of the same row is zero.
for example.
ColumnA Column B ColumnC ColumnD ColumnE
row1- abc xyz 0 abs abx
row2- wqe tuy 0 0 0
row3 uhiu khj kjh khk 0
here I have to delete the row 2 only because values of all column c , D , E are zero
Please help
A reverse loop should do the job. Try the below:
Option Explicit
Public Sub DeleteRows()
Dim i As Long, count As Long, lastRow As Long
' Replace Sheet1 with your sheetname
With ThisWorkbook.Worksheets("Sheet2")
' Change C with your most consistent column letter
' (a column that has data always to make sure there's no possibility to miss the last row due to empty cells)
lastRow = .Cells(.Rows.count, "C").End(xlUp).Row
' We do a reverse loop to not screw up the index
For i = lastRow To 2 Step -1
If .Range("C" & i).Value = "0" And .Range("D" & i).Value = "0" And .Range("E" & i).Value = "0" Then
.Range("C" & i).EntireRow.Delete
count = count + 1
End If
Next i
End With
' Display some message
If count > 0 Then
MsgBox "Done!" & vbCrLf & "Deleted " & count & " row(s).", vbInformation + vbOKOnly, "Success"
Else
MsgBox "No matches found for deletion", vbInformation + vbOKOnly, "Success"
End If
End Sub
Try,
Sub test()
Dim vDB, vR()
Dim Ws As Worksheet, toWs As Worksheet
Dim i As Long, n As Long
Dim j As Integer
Set Ws = ActiveSheet
vDB = Ws.UsedRange
For i = 1 To UBound(vDB, 1)
If vDB(i, 3) = 0 And vDB(i, 4) = 0 And vDB(i, 5) = 0 Then
Else
n = n + 1
ReDim Preserve vR(1 To 5, 1 To n)
For j = 1 To 5
vR(j, n) = vDB(i, j)
Next j
End If
Next i
Set toWs = Sheets.Add '<~~ set your sheet
With toWs
.Cells.Clear
.Range("a1").Resize(n, 5) = WorksheetFunction.Transpose(vR)
End With
End Sub
Try this code, fast and easy code.
Sub deleterow()
Dim i As Integer
i = 2
LastR = Cells(Rows.Count, 1).End(xlUp).row
For i = LastR To 2 Step -1
If Cells(i, 3).value = "0" And Cells(i, 4).value = "0" And Cells(i, 5).value = "0" Then
Cells(i, 1).EntireRow.delete
End If
Next i
End Sub

Create ranges out of rows VBA

I have multiple rows which are sometimes in order and sometimes not.
Out of rows which are in order, I would need to create a range, which are not in order just to copy the number.
The thing is, the most rows in order can be even 20.
For example cells:
1
3
5
6
7
8
9
10
13
14
15
There would be:
1
3
5-10
13-15
Is it possible to code it?
Thanks
Assuming your data starts with A1.... and
required results will be printed at C column.
Try with below code
Sub test()
Dim i As Long, lastrow As Long, incre As Long
Dim startno As Variant
Dim endno As Variant
incre = 1
lastrow = Range("A" & Rows.Count).End(xlUp).Row
For i = 1 To lastrow
If Cells(i, 1) = (Cells(i + 1, 1) - 1) Then
startno = Cells(i, 1)
Do While Cells(i, 1) = (Cells(i + 1, 1) - 1)
endno = Cells(i + 1, 1)
i = i + 1
Loop
Cells(incre, 3) = "'" & startno & "-" & endno
incre = incre + 1
Else
Cells(incre, 3) = Cells(i, 1)
incre = incre + 1
End If
Next i
End Sub
if you want the address of all consecutive ranges you could use:
Option Explicit
Sub main()
Dim rangeStrng As String
With Worksheets("MyRowsSheet") '<--| change "MyRowsSheet" with your actual sheet name
rangeStrng = .Range("A1", .Cells(.Rows.Count, "A").End(xlUp)).SpecialCells(xlCellTypeConstants).Areas.Parent.Address(False, False)
End With
End Sub
if you want only the rows range then you could use:
Option Explicit
Sub main2()
Dim rng As Range
Dim rowsRangeStrng As String
With Worksheets("MyRowsSheet") '<--| change "MyRowsSheet" with your actual sheet name
For Each rng In .Range("A1", .Cells(.Rows.Count, "A").End(xlUp)).SpecialCells(xlCellTypeConstants).Areas
If rng.Rows.Count = 1 Then
rowsRangeStrng = rowsRangeStrng & rng.Rows(1).Row & ","
Else
rowsRangeStrng = rowsRangeStrng & rng.Rows(1).Row & "-" & rng.Rows(rng.Rows.Count).Row & ","
End If
Next rng
End With
If rowsRangeStrng <> "" Then rowsRangeStrng = Left(rowsRangeStrng, Len(rowsRangeStrng) - 1)
End Sub
If I understood your question correctly, you are not looking to address a range, but rather want an output table. This code below should provide you with just that. My input numbers are in column A, and the output is in column B.
Sub sequentials()
Dim tws As Worksheet
Dim tmpRowA, tmpRowB As Integer
Dim seq() As Long
Dim frA, frB, lrA As Integer 'firstrow col A, col B, lastrow of data
Set tws = ThisWorkbook.Worksheets("Sheet1")
frA = 2
frB = 2
lrA = tws.Range("A1000000").End(xlUp).Row
'Input in column A, Output in column B
'Headers in Row 1
ReDim seq(0 To lrA - 1)
seq(0) = -2
seq(1) = tws.Range("A" & frA).Value
tmpRowA = frA
tmpRowB = frB
tws.Range("B" & frB & ":B" & lrA).NumberFormat = "#"
For r = frA + 1 To lrA
If r = 23 Then
r = 23
End If
With tws
seq(r - 1) = .Range("A" & r).Value
If seq(r - 1) = seq(r - 2) + 1 Then
If r = lrA Then
.Range("B" & tmpRowB).Value = .Range("A" & tmpRowA - 1).Value & "-" & seq(r - 1)
End If
Else
If seq(r - 2) = seq(r - 3) + 1 Then
.Range("B" & tmpRowB).Value = .Range("A" & tmpRowA - 1).Value & "-" & seq(r - 2)
Else
.Range("B" & tmpRowB).Value = seq(r - 2)
End If
tmpRowB = tmpRowB + 1
tmpRowA = r + 1
If r = lrA Then
.Range("B" & tmpRowB).Value = seq(r - 1)
End If
End If
End With
Next r
End Sub
Proof of concept:

VBA code to find the sum of unique elements in a range

I have 2 columns and need a VBA code to sum the values of unique elements in column "A", print the unique elements in column "D" and sum in column "E" :-
Name Value Name Sum
A 1 A 13
A 2 B 7
B 1 C 3
B 3
C 2
A 1
B 2
A 3
B 1
A 2
A 4
C 1
Can anyone help on this, this is what I tried :-
Sub CountSum()
Dim c As Collection, wf As WorksheetFunction, _
K As Long, N As Long, i As Long, _
v As Variant, d As Collection, y As Variant
Set c = New Collection
Set d = New Collection
Set wf = Application.WorksheetFunction
K = 2
N = Cells(Rows.Count, "A").End(xlUp).Row
On Error Resume Next
For i = 2 To N
v = Cells(i, "A").Value
y = Cells(i, "B").Value
c.Add v, CStr(v)
d.Add y
If Err.Number = 0 Then
Cells(K, "D").Value = v
Cells(K, "E").Value = wf.CountIf(Range("A:A"), v)
Cells(K, "F").Value = wf.Sum(Range("B:B"), y)
K = K + 1
Else
Err.Number = 0
End If
Next i
On Error GoTo 0
End Sub
Using a Dictionary:
Sub Tester()
Dim rng As Range, dict As Object
Set rng = Range(Range("A2"), Cells(Rows.Count, 1).End(xlUp)).Resize(, 2)
Set dict = SubTotals(rng, 1, 2)
DumpDict dict, Range("D1")
End Sub
Function SubTotals(rng As Range, colKey As Long, colVal As Long) As Object
Dim rv As Object, rw As Range, k, v
Set rv = CreateObject("scripting.dictionary")
For Each rw In rng.Rows
k = rw.Cells(colKey).Value
v = rw.Cells(colVal).Value
If Not IsError(k) And Not IsError(v) Then
If Len(k) > 0 And IsNumeric(v) Then
rv(k) = rv(k) + v
End If
End If
Next rw
Set SubTotals = rv
End Function
Sub DumpDict(dict As Object, rng As Range)
Dim i As Long, k
i = 0
For Each k In dict.keys
With rng.Cells(1)
.Offset(i, 0).Value = k
.Offset(i, 1).Value = dict(k)
End With
i = i + 1
Next
End Sub
next code works for me, I hope this will help you. This will work perfectly if at column A there are not blank cells between values.
Sub SUM()
Dim i, j, k As Integer
i = 2
j = 2
Range("D1").Value = "NAME"
Range("E1").Value = "VALUE"
'copy the first value of column A to column D
Range("D2").Value = Range("A2").Value
'cycle to read all values of column B and sum it to column E; will run until find a blank cell
While Range("A" & i).Value <> ""
'this check if actual value of column A is equal to before value of column A, if true just add the column B value to E
'else, look for the row in column D where is the same value of column A, if it doesn't exist code create the value
'in column D and E
If Range("A" & i).Value = Range("A" & i - 1).Value Then
Range("E" & j).Value = Range("E" & j).Value + Range("B" & i).Value
Else
flag = 1
While Range("D" & flag).Value <> ""
If Range("A" & i).Value = Range("D" & flag).Value Then
j = flag
Range("E" & j).Value = Range("E" & j).Value + Range("B" & i).Value
flag = Range("D1").End(xlDown).Row
Else
j = 0
End If
flag = flag + 1
Wend
If j = 0 Then
Range("D1").End(xlDown).Offset(1, 0).Value = Range("A" & i).Value
Range("E1").End(xlDown).Offset(1, 0).Value = Range("B" & i).Value
j = Range("E1").End(xlDown).Row
End If
End If
i = i + 1
Wend
MsgBox "End"
End Sub

Resources