Insert rows based on cell values of a column - excel

I am new to VBA, just trying my hands as my requirement is not getting fulfilled by formulas.
Depending on the entry in the cell E2..E3..in column E, new rows to be inserted in another sheet.Also copy the value of A, B & C from sheet 1 to A, C, D of sheet 2 respectively. Column B of Sheet 2 will/should automatically generate the line item no.
for example: if E2 = 2 in Sheet1, then 2 new rows to be added with copied data of A2, B2 and C2 of Sheet 1 into Sheet2.
Please check the attached images:
Sheet1
Sheet2
After going through the forum help, I have tried some coding but this for only one cell value, but I need the code to work for each cell value. Which I am not able to do. Also the line item number (Col B) is coming like 3..2..1 not 1..2..3.
Please check the code:
Code
Regards,
Krish

'Hope this Works for you
Sub transfer_data()
Dim arr() As Variant
Dim cnt, n As Long
arr = Application.Transpose(Application.Transpose(Sheets("Sheet1").Range("A2:E22")))
n = 1
i = 0
For i = LBound(arr) To UBound(arr)
Sheets("Sheet2").Range("A" & n).Value = arr(i, 1)
Sheets("Sheet2").Range("B" & n).Value = arr(i, 5)
Sheets("Sheet2").Range("c" & n).Value = arr(i, 3)
Sheets("Sheet2").Range("D" & n).Value = arr(i, 2)
cnt = arr(i, 5)
n = n + cnt
Next i
End Sub

Related

Cross reference 2 different columns, then put count of values in another table

I have a worksheet, and I want to be able to go through one column (O) to find the different values, then go to another column (U) and count whether the sting is paper or electronic. Then, I want to be able to take the total of paper/electronic stings from U with each instance in O (source) and put it into the following table on a different sheet with VBA.
Due to the sensitivity of the data, I quickly made a table with basically what I mean. Pretend A is O and B is U.
And I want the output in this table, or if there is a better way to present the data:
I've tried making a pivot table, but it simply counts each instance of the paper/electronic string in the sheet, and I need to cross reference the values in O with U.
Here is the formula what you desire. Remember that we need to change source value and Fillining medium value in each row. you can see from the image that in formula for Source A values are "A" and "Paper" for paper count and "A" and "Electronic" for electronic count. the formulas for Source A are written at the bottom of the table and formula for Source C you can See from formula Bar. This is to show you the change you need to make in formula for each source.
if you have excel 365 you can just use the unique/countifs function. For simplicity I assume your data is in col A & B
To get the unique values (source) col E:
=UNIQUE(A:A)
To count (manually add "paper" as header in col F:
=COUNTIFS(A:A;E2;B:B;$F$1)
Do the same for the other values.
EDIT:
Anything can be done in code:
Option Explicit
Sub DictUniqueFinal()
Dim arr, arr2, arrH, j As Long, dict As Object, id As String
'setup some arrays
arrH = Split("Source, Paper, Electronic", ",")
arr = Sheet1.Range("A1").CurrentRegion.Offset(1, 0).Value2 'load source without headers
ReDim arr2(1 To UBound(arr), 1 To 3)
'setup the dict
Set dict = CreateObject("Scripting.Dictionary") 'create dictionary lateB
For j = 1 To UBound(arr) - 1 'traverse source
id = arr(j, 1)
If Not dict.Exists(id) Then 'create key
If arr(j, 2) = "paper" Then
dict.Add id, 1 & "," & 0
Else
dict.Add id, 0 & "," & 1
End If
Else 'update key
If arr(j, 2) = "paper" Then
dict(id) = Split(dict(id), ",")(0) + 1 & "," & Split(dict(id), ",")(1)
Else
dict(id) = Split(dict(id), ",")(0) & "," & Split(dict(id), ",")(1) + 1
End If
End If
Next j
'build final array
ReDim arr2(0 To dict.Count - 1, 1 To 3)
For j = 0 To dict.Count - 1
arr2(j, 1) = dict.Keys()(j)
arr2(j, 2) = Split(dict.Items()(j), ",")(0)
arr2(j, 3) = Split(dict.Items()(j), ",")(1)
Next j
'dump to sheet
With Sheet2
.Range(.Cells(1, 1), .Cells(1, UBound(arrH) + 1)).Value2 = arrH
.Range(.Cells(2, 1), .Cells(UBound(arr2) + 2, UBound(arr2, 2))).Value2 = arr2
End With
End Sub
It's a bit long and I had to hard code, but I found a solution, thanks to #AnmolKumar I looked in to Countif and found this:
ws2.Range("F15").Value2 = Excel.WorksheetFunction.CountIfs, _
(ws3.Range("O1:O" & lstRow2), "A", ws3.Range("U1:U" & lstRow2), "Paper")
I'll just have to do it for each different section

Copy values based on criteria with macro

I have 2 columns, one with dates (column A:A, of type dd/mm/yyyy hh:mm) the other with values of a parameter (column B:B), registered at each date. But not all dates have registered values (in which case in column B I will have -9999.
What I need is to copy to other columns (say D:D and E:E) only the cells where there is a value other than -9999 and the correspondent date too. For example:
Example
My data series is pretty long, it can get to 10000 or more lines, so I cannot do this selection “manually”. I would prefer macros, not array formulae, because I want to choose the moment of the calculation.
This code should do what you are looking for. This will copy all rows with a value in column B, into columns D and E.'
Sub copyrows()
Dim RowNo, newRowNo As Long
RowNo = 2
newRowNo = 2
With ThisWorkbook.ActiveSheet
.Cells(1, 4).Value = "Date"
.Cells(1, 5).Value = "H_Selected"
Do Until .Cells(RowNo, 1) = ""
If .Cells(RowNo, 2) <> "-9999" Then
.Cells(newRowNo, 4) = .Cells(RowNo, 1)
.Cells(newRowNo, 5) = .Cells(RowNo, 2)
newRowNo = newRowNo + 1
End If
RowNo = RowNo + 1
Loop
End With
End Sub

MS Excel: macro inquiry for array

lets say in column A:Row 2, I have a score of 45 and in column B, I have the amount of people that got that score. what i then want to do is on column D, output that score X amount of times. x=repitition.
in the exmaple 5 people got a score of 45 so in column D i want to insert 5 scores of 45. then I see in column A:Row2 3 people got a score of 46 then after the last 45, in column D I want to append 46 3 times.. and so on..
Could someone show me how to do this?
Here you go:
Sub test_scores_repitition()
'run with test scores sheet active
r = 1
dest_r = 1
Do While Not IsEmpty(Range("a" & r))
If IsEmpty(Range("b" & r)) Then Range("b" & r).Value = 0 'if there's no quantity listed for a score, it assumes zero
For i = 1 To Range("b" & r).Value
Range("d" & dest_r).Value = Range("a" & r).Value
dest_r = dest_r + 1
Next i
r = r + 1
Loop
End Sub
Macro answer:
Sub WriteIt()
Dim lrow As Long
Dim WriteRow As Long
Dim EachCount As Long
Dim ReadRow As Long
' find last in list of numbers
lrow = Range("A1").End(xlDown).Row
'start at 2 because of headers
WriteRow = 2
ReadRow = 2
While ReadRow <= lrow
For EachCount = 1 To Cells(ReadRow, 2)
'repeat the number of times in column B
Cells(WriteRow, 4) = Cells(ReadRow, 1)
'the number in column A
WriteRow = WriteRow + 1
Next
ReadRow = ReadRow + 1
'and move to the next row
Wend
'finish when we've written them all
End Sub
it is possible with a formula, just not really recommended as it looks auful, and would be difficult to explain. It uses a Microsoft formula to count the number of unique items in the data above, and once it counts the number it is supposed to write of the number above, it moves to the next number. The formula does not know where to stop, and will put 0 when it runs out of data.
in D2, put =A2
In D3, and copied down, put
=IF(COUNTIF($D$2:D2,OFFSET($A$1,SUM(IF(FREQUENCY($D$2:D2,$D$2:D2)>0,1)),0))<OFFSET($B$1,SUM(IF(FREQUENCY($D$2:D2,$D$2:D2)>0,1)),0),OFFSET($A$1,SUM(IF(FREQUENCY($D$2:D2,$D$2:D2)>0,1)),0),OFFSET($A$1,SUM(IF(FREQUENCY($D$2:D2,$D$2:D2)>0,1))+1,0))

Merge the cell values if duplicates exist

I want to merge the values in column B if Duplicates exist in Column A
A B
123 A
123 B
123 C
456 D
456 E
789 F
My output should look like this
A B
123 A B C
456 D E
789 F
I have a large amount of data and it is hard to do it manually ,So u guys have any idea to do it in macros in Excel?
Any help will be appreciated..Thanks in Advance
I'd cheat, and use formulas as follows;
1) Sort by column A
2) In col C, add a formula to test if the current one is last (assuming there's a header, put this in C2
=if(A2<>A3,TRUE,FALSE)
Now, this should only be true for the last cell in a series of same ID's
3) in Col D, add a formula for concatenating if the ID's are the same,
=if(A2=A1,D1&" "&B2,B2)
4) Filter on column C to show only the last cell in each series.
Cheers.
In case you want the resultant data in the same cells the original data existed ie not in Cell 10, then you have to store the source data in a two dimensional array. Then from the array we have use the above code to insert the data in the same place the original data existed. Here goes the listing to accomplish the task:
Private Sub Worksheet_BeforeDoubleClick(ByVal Target As Range, Cancel As Boolean)
Dim names(2 To 7, 2)
For i = 2 To 7
names(i, 1) = Cells(i, 1)
names(i, 2) = Cells(i, 2)
Next
On Error Resume Next:
Sheet1.Cells.Clear
cnt = 2
For i = 2 To 7
strg = strg + names(i, 2)
If names(i + 1, 1) <> names(i, 1) Then
Cells(cnt, 1) = names(i, 1)
Cells(cnt, 2) = strg
cnt = cnt + 1
strg = ""
End If
Next
End Sub
Please note that I have declared names array with two dimesnions to store the data. Then the array is searched to get the result.
You can use the following macro:
Private Sub Worksheet_BeforeDoubleClick(ByVal Target As Range, Cancel As Boolean)
cnt = 10
For i = 2 To 7
strg = strg + Cells(i, 2)
If Cells(i + 1, 1) <> Cells(i, 1) Then
Cells(cnt, 1) = Cells(i, 1)
Cells(cnt, 2) = strg
cnt = cnt + 1
strg = ""
End If
Next
End Sub
The requested data will be printed from Cells 10

Check if any rows are duplicate and highlight

I have data in (Sheet4) columns A to I:
I'm trying to compare data for all rows (Only on column A and B) to see if any of the rows is duplicated, if it is: excel should highlight both rows.
Example:
A B C......I
s 1 x
s 3 w
e 5 q
s 1 o
Row 1 and 4 should be highlighted as values are the same for column A and B.
I shouldn't modify the sheet (no modification to the columns or rows should be done to the sheet), and the number of rows is not always known (not the same for all files).
Is there an easy way (using macros) to do this???
This is an attempt I have tried, but it is increasing my file to 7MB!!!!! I'm sure there should be an easier way to compare rows for an unknown number of rows and just highlight the dupllicates if they exist:
Public Sub duplicate()
Dim errorsCount As Integer
Dim lastrow As Integer
Dim lastrow10 As Integer
errorsCount = 0
lastrow = Sheet4.Cells(Rows.Count, "A").End(xlUp).Row 'is the row number of the last non-blank cell in the specified column
lastrow10 = lastrow
Sheet10.Range("B1:B" & lastrow10).Value = Sheet4.Range("A1:A" & lastrow).Value
Set compareRange = Sheet10.Range(column + "2:" & Sheet10.Range(column + "2").End(xlDown).Address)
For Each a In Sheet10.Range(column + "2:" & Sheet10.Range(column + "2").End(xlDown).Address)
c = a.Value
If c <> Null Or c <> "" Then
If name = "testing" Then
If WorksheetFunction.CountIf(compareRange, c) > 1 Then
a.Interior.ColorIndex = 3
errorsCount = errorsCount + 1
End If
End If
End If
Next a
If errorsCount > 0 Then
MsgBox "Found " + CStr(errorsCount) + " errors"
Else
MsgBox " No errors found."
End If
End Sub
Silly answer to you.
J1 or just duplicate sheet.
J1 =CONCATENATE(A1,"#",B1) > drag down > J:J > conditional format > highlight cells rules > duplicate values.
(* replace the # to any string which you think not possible in the original A:A and B:B.)
I do this all the time.
To collect all duplicates just SORT with color.

Resources