VBA to auto increment row number into a new column in Excel - excel

I have existing script that does a major chunk of what I need. The script (from here: https://www.extendoffice.com/documents/excel/4054-excel-duplicate-rows-based-on-cell-value.html) basically inserts and then copies rows of data X number of times, where X is one of the fields in the table. It works well and the referenced page shows examples of the start and end points.
But when I run the script in Excel I go from ~2,000 lines in my table to ~40,000 lines. I need to modify all the duplicated rows (incremental dates) and so I am now attemting to also include new data into the table while the script runs that will allow me to change data in the duplicated rows... for example I can use the duplicate number 1, 2, 3, 4 and some simple formulas to change dates relative to a start point.
I expect that I will need some additional code inserted into the routine that will add data into a nominated column and do the auto incrementing from 1.
Having zero actual VBA skillz, ive no idea how to tackle the second part of my problem with the code I already have. Any help would be totally awesome !!
Sub CopyData()
'Updateby Extendoffice 20160922
Dim xRow As Long
Dim VInSertNum As Variant
xRow = 1
Application.ScreenUpdating = False
Do While (Cells(xRow, "A") <> "")
VInSertNum = Cells(xRow, "D")
If ((VInSertNum > 1) And IsNumeric(VInSertNum)) Then
Range(Cells(xRow, "A"), Cells(xRow, "D")).Copy
Range(Cells(xRow + 1, "A"), Cells(xRow + VInSertNum - 1, "D")).Select
Selection.Insert Shift:=xlDown
xRow = xRow + VInSertNum - 1
End If
xRow = xRow + 1
Loop
Application.ScreenUpdating = False
End Sub

Try this code below, I used the same sample data on the link you provided. However on this code I created 2 worksheets, one for the raw data to be processed and one for the duplicate output including the increment of dates and duplicate number.
Sub duplicateData()
Dim rSH As Worksheet
Set rSH = ThisWorkbook.Sheets("RAW") 'Your raw data
Dim oSH As Worksheet
Set oSH = ThisWorkbook.Sheets("OUTPUT") 'Output data on another sheet
x = 2
For a = 2 To rSH.Range("A" & Rows.Count).End(xlUp).Row
For b = 1 To rSH.Cells(a, 4).Value '4 is the column of duplicate times
If b = 1 Then
For c = 1 To 4 'Number of your column
oSH.Cells(x, c).Value = rSH.Cells(a, c).Value
Next c
oSH.Cells(x, 5) = 1 'First instance, 5 is the column number of duplicate counter
Else
For c = 1 To 4 'Number of your column
oSH.Cells(x, c).Value = rSH.Cells(a, c).Value
Next c
oSH.Cells(x, 3).Value = CDate(oSH.Cells(x - 1, 3).Value) + 1 '3 is the column number of date to increment
oSH.Cells(x, 5).Value = CInt(oSH.Cells(x - 1, 5).Value) + 1 '5 is the column number of duplicate counter
End If
x = x + 1 'Increment Output row number
Next b
Next a
End Sub

Related

Excel VBA Sort not 100% correct

New to the forum and hope someone can help.
Create a function to loop through a set of data row by row for sorting.
Firstly need to check if column 1 is not equal to 9999. If not insert into the appropriate row using column 1 as the sort criteria. If it equals 9999 then insert into the appropriate spot using column 3 and column 2.
The problem I'm encountering is that some row and not sort. I think its because as I'm cutting and pasting the row is missed. Below is my code and the sample data
Sub insertionTableSort()
'PURPOSE: loop through all employee and apply the sort as follows:
'1) Seniority <> 9999 Seniority number
'2) Seniority = 9999 sort start date then employee number
Dim ws As Worksheet
Dim tbl As ListObject
Set ws = ThisWorkbook.Worksheets("Roster Applications")
Set tbl = ws.ListObjects("RosterRequest") '## modify to your table name.
Set tblRow = tbl.ListRows
'Loop Through Every Row in Table
For x = 2 To tbl.Range.Rows.Count - 1
'Debug.Print x & ", " & tbl.DataBodyRange(x, 1).Value, tbl.DataBodyRange(x, 2).Value, tbl.DataBodyRange(x, 4).Value
For y = 2 To tbl.Range.Rows.Count
'seniroity = 9999
If tbl.DataBodyRange(x, 1) = 9999 Then
'sort by start date then Staff Num
If tbl.DataBodyRange(x, 4) < tbl.DataBodyRange(y - 1, 4) And tbl.DataBodyRange(x, 2) < tbl.DataBodyRange(y - 1, 2) Then
tbl.ListRows(x).Range.Cut
tbl.ListRows(y - 1).Range.Insert
Exit For
End If
Else
'seniroity <> 9999
'sort by seniority
If tbl.DataBodyRange(x, 1) < tbl.DataBodyRange(y - 1, 1) Then
tbl.ListRows(x).Range.Cut
tbl.ListRows(y - 1).Range.Insert
Exit For
End If
End If
Next y
Next x
End Sub
sample data after running the above
sorts well until this point where row 2 should be before row 1 and there are other examples
Data initially sort by Register No.
Errors highlighted in yellow
Finished Sort

How to add values from different sheets, and retain the formula pointing to the sheets+cells?

I am trying to add values from different sheets (Sheet 2 to 5) into my main sheet (Sheet 1). In Sheet 1 I want the cells to contain the right formula pointing to the different sheets (if possible).
Typically like this:
='Sheet2'!D5+'Sheet3'!D165
All my sheets have different products, but some sheets contain same products. So I want to search through them all and ADD them in my Main Sheet (Sheet 1).
Sub UpdateMainSheet()
' Kode for å Oppdatere Plukkeliste Alle Artikler Summert
Dim AktivtArk As String
Dim AktivtArkNavn As String
Dim K As Integer
Dim Count As Integer
'Line of code to delete old data in Main Sheet:
Worksheets("Sheet1").Range("A2:H10000").Clear
AktivtArkOverskrift = "List of Articles from Sheet 2 to 5"
'Creates Headline in Main Sheet:
eRow = Sheet1.Cells(Rows.Count, 1).End(xlUp).Offset(1, 0).Row
Worksheets("Sheet1").Cells(eRow, 1) = AktivtArkOverskrift
Worksheets("Sheet1").Cells(eRow, 1).Font.Bold = True
'Script to check and gather data from the other sheets (Sheet 2, 3, 4 and 5):
For K = 2 To 5
'For loop to check each line in sheet "K"
For I = 2 To 1000
'If function to check if the cell I in column F is empty, if so it_jumps to next row and do the same check:
If Worksheets(K).Cells(I, 6) > 0 Then
Count = 0
'For loop to check if I already have a row in the Main Sheet with the article I'm checking:
For L = 2 To 1000
'If function to check if the articles have the same article number:
If Worksheets(K).Cells(I, 1) = Worksheets("Sheet1").Cells(L, 1) Then
'Line of code that are supposed to ADD the values that is currently in the Main Sheet, togheter with the value in Sheet K:
Worksheets("Sheet1").Cells(I, 4).Formula = Worksheets("Sheet1").Cells(I, 4) + Worksheets(K).Cells(L, 4)
End If
Next L
End If
Next I
Next K
End Sub
So what I need to fix in my code is this part (located furthest inside the For Loop):
Worksheets("Sheet1").Cells(I, 4).Formula = Worksheets("Sheet1").Cells(I, 4) + Worksheets(K).Cells(L, 4)
And make it create a formula in the wanted cell, that looks something like this:
='Sheet2'!D5+'Sheet3'!D165
It must be able to add another cell as well, since the Loop are running through several Sheets (Sheet 2 to 5) that may contain the same products.
I.e. I only want one line in my Main Sheet for each product.
I managed to find the solution in the end.
It seemed I had switched the L and I in som of the looping, which resulted in the values not to be added togheter.
The following code (I did not translate to English, but can do this if someone wants/need it) solved my issue, and gave me the values from Sheet 2 to 5 sorted by product in Sheet 1:
Sub OppdaterePlukkelisteSummert()
'Kode for å Oppdatere Plukkeliste Alle Artikler Summert
Dim AktivtArk As String
Dim AktivtArkNavn As String
Dim K As Integer
Dim Teller As Integer
Dim value1 As Integer
Dim value2 As Integer
'Sletter Plukklisten for å oppdatere og sortere på nytt:
Worksheets(1).Range("A2:H10000").Clear
'HENTING AV DATA FRA ARKET "K":
AktivtArk = "Artikler Summert fra Alle Ark"
AktivtArkOverskrift = "Artikler Summert fra Alle Ark"
'Setter inn Overskrift som Forteller kva ark utstyret kommer fra:
eRow = Sheets(1).Cells(Rows.Count, 1).End(xlUp).Offset(1, 0).Row
Worksheets(1).Cells(eRow, 1) = AktivtArkOverskrift
Worksheets(1).Cells(eRow, 1).Font.Bold = True
'Sjekker hvilke/hvilket rader/utstyr som skal plukkes, og legger det inn i "Ark1":
For K = 2 To 5
For I = 2 To 1000
If Worksheets(K).Cells(I, 6) > 0 Then
Teller = 0
For L = 2 To 1000
If Worksheets(K).Cells(I, 1) = Worksheets(1).Cells(L, 1) Then
value1 = Worksheets(1).Cells(L, 4)
value2 = Worksheets(K).Cells(I, 4)
Worksheets(1).Cells(L, 4) = value1 + value2
Worksheets(1).Cells(L, 6) = value1 + value2
Else
Teller = Teller + 1
End If
Next L
If Teller > 998 Then
eRow = Sheets(1).Cells(Rows.Count, 1).End(xlUp).Offset(1, 0).Row
For J = 1 To 11
Worksheets(1).Cells(eRow, J) = Worksheets(K).Cells(I, J)
Next J
Worksheets(1).Cells(eRow, 6).Font.Color = RGB(0, 150, 0)
Worksheets(1).Cells(eRow, 7).Font.Color = RGB(0, 150, 0)
End If
End If
Next I
Next K
Worksheets(1).Range("A2").Select
End Sub
I hope this can be useful for someone else :-)
All help and suggestion in the comments are appreciated!
I was going to illustrate with this simple example:
I = 1 'for example
For K = 2 To 5
Worksheets("Sheet1").Cells(I, 4).Value = Worksheets("Sheet1").Cells(I, 4).Value + _
WorksheetFunction.SumIf(Worksheets(K).Range("A:A"), "Bananas", Worksheets(K).Range("D:D"))
Next K

Logic issue at the end of a loop

I have a spreadsheet with a column filled with strings. There are sometimes several instances of one string (I've sorted it though so they're all grouped together) so I've created a macro that looks at the current row in the column, determines if its already been posted in the second worksheet, and if it has, it moves to the next row, if it hasn't it posts it and then moves on.
It works perfectly until the end where it completely ignores the last entry. The last entry is one of the instances where there's several of the same strings so the issue almost definitely isn't that its just ignoring the last row.
It's ignoring the last entry completely no matter how many times it repeats. New to vba so any help appreciated.
Sub RCFS()
Dim ProfCtr As String
Dim S2FreecellH As Long
Dim ProfCenCellH As Long
S2FreecellH = 3
ProfCenCellH = 2
ProfCtr = Cells(ProfCenCellH, 4)
Worksheets("Sheet2").Cells(S2FreecellH, 1).Value = ProfCtr
While IsEmpty(Cells(ProfCenCellH, 4).Value) = False
If Cells(ProfCenCellH, 4).Value <> ProfCtr Then
Worksheets("Sheet2").Cells(S2FreecellH, 1) = ProfCtr
S2FreecellH = S2FreecellH + 1
ProfCtr = Cells(ProfCenCellH, 4)
ProfCenCellH = ProfCenCellH + 1
Else
ProfCenCellH = ProfCenCellH + 1
End If
Wend
End Sub
Indeed, your loop needs to still flush the value of ProfCtr even when you reached the empty cell. You can make it work by looking ahead one row in your If condition (add + 1).
Also included a couple of other improvements:
Do While Not IsEmpty(Cells(ProfCenCellH, 4).Value)
If Cells(ProfCenCellH + 1, 4).Value <> ProfCtr Then
Worksheets("Sheet2").Cells(S2FreecellH, 1) = ProfCtr
S2FreecellH = S2FreecellH + 1
ProfCtr = Cells(ProfCenCellH, 4)
End If
ProfCenCellH = ProfCenCellH + 1
Loop
Let me see if I have this right
' Stop when you reach an empty cell
While IsEmpty(Cells(ProfCenCellH, 4).Value) = False
' If the cell's value matches the variable ProfCtr then
' ignore it and move to the next row.
If Cells(ProfCenCellH, 4).Value <> ProfCtr Then
' But if it -doesn't- match, then copy the variable
' ProfCtr to Sheet 2.
Worksheets("Sheet2").Cells(S2FreecellH, 1) = ProfCtr
' Increment your rows
S2FreecellH = S2FreecellH + 1
' Set the next bit of text to copy
ProfCtr = Cells(ProfCenCellH, 4)
ProfCenCellH = ProfCenCellH + 1
Else
ProfCenCellH = ProfCenCellH + 1
End If
Shouldn't you be setting Prof Ctr = Cells(ProfCenCelH, 4) BEFORE doing the copying over to Sheet2?
trincot has the correct answer. Here is an alternate technique, using built-in method, that will accomplish the same task.
With Worksheets("Sheet1")
.Range("D1", .Range("D" & .Rows.Count)).AdvancedFilter Action:=xlFilterCopy, CopyToRange:=Sheet2.Range("A1"), Unique:=True
End With

How to get the value of another cell if the only addition to the referenced cell is "-LA" or "-LED'

So I have a full sheet of item numbers that need to be updated for quantities on a daily basis. There are many items that contain two accessories as different item numbers such as what is shown below:
1114
1114-LA
15894/3
1114-LED
What I need to happen is for the value(quantity) of the two numbers with the -LA and -LED to equal the original item number's (ex. 1114) quantity. Some items have no other option and some only have one or the other, and some have both.
Any Ideas on how I could do this? The spreadsheet is several thousand numbers long.
here is what it looks like:
Item number Quantity
1114 5
1114-LA 0
1114-LED 0
225896/3 2
225896-LED 0
114895 8
114895-LED 91
114895-LA 0
115938/2 91
115938/2-LED 0
edited after OP's data pattern change
assuming, as per your example, that:
unknown accessories per item number
accessories follow immediately after item number
quantities are in column adjacent item numbers one
you can try this:
Sub main()
Dim iRow As Long
iRow = 1
Do While iRow < Cells(Rows.Count, 1).End(xlUp).Row '<--| change '1' to your actual columnn with item numbers index
If InStr(Cells(iRow, 1).Value, "-") = 0 Then
Do While InStr(Cells(iRow + 1, 1).Value, "-") > 0
Cells(iRow + 1, 2).Value = Cells(iRow, 2).Value
iRow = iRow + 1
Loop
Else
iRow = iRow + 1
End If
Loop
End Sub
while an alternative Autofilter() + "Formula" approach is the following:
Sub main2()
With Range("B1", Cells(Rows.Count, 1).End(xlUp)) '<--| assuming data are in range "A1:Bx" with row 1 headers
.AutoFilter field:=1, Criteria1:="*-*"
With .Resize(.Rows.Count - 1, 1).Offset(1, 1)
.SpecialCells(xlCellTypeVisible).FormulaR1C1 = "=R[-1]C"
.Parent.AutoFilterMode = False
.Value = .Value
End With
End With
End Sub
where row 1 must be a "header" row

Inserting new row in excel by VBA

I have an excel spreadsheet. In a column of the spreadsheet I have a list of codes (numbers).These codes (numbers) are sorted from highest to lowest values.(some of these codes has been repeated. For example I have three consecutive line with code 1001200).I want to insert new rows between each codes (in case of having repeated codes i just need one new row (for example i Just need one new row for 1001200 not 3 rows) .
I have written the following code but it does not work.
Sub addspace()
Dim space_1(5000), Space_2(5000)
For n = 1 To 5000
Debug.Print space_1(n) = Worksheets("sheet3").Cells(1 + n, 1).Value
Debug.Print Space_2(n) = Worksheets("sheet3").Cells(2 + n, 1).Value
Next
For n = 1 To 5000
If space_1(n) <> Space_2(n) Then
Range("space_1(n)").EntireRow.Insert
End If
Next
End Sub
How can I fix it? (From the code you can see that I am so beginner :)))
Cheers
To insert one empty row between each unique value try this:
Option Explicit
Public Sub addspace()
Dim i As Long
Application.ScreenUpdating = False
With Worksheets("sheet3")
For i = 5000 To 2 Step -1
While .Range("A" & i - 1) = .Range("A" & i)
i = i - 1
Wend
.Rows(i).Insert Shift:=xlDown
Next
End With
Application.ScreenUpdating = True
End Sub
It starts from the end row and moves up, skipping duplicates
The Range("space_1(n)") is invalid. Arg of range object should be a column name like "A1", you can use Range("A" & n).EntireRow.Insert in your code. But I recommend my code.
Please try,
Sub addspace()
Dim n As Integer
For n = 1 To 5000
If Worksheets("sheet3").Cells(n, 1).Value <> Worksheets("sheet3").Cells(n + 1, 1).Value Then
Worksheets("sheet3").Cells(n + 1, 1).EntireRow.Insert
n = n + 1
End If
Next
End Sub

Resources