Attempting to Write a Loop in VBA - vba

I am currently trying to write a short loop to condense a list of received items into a concise itemized report. I scan the barcode of each item I receive and it goes into Column A, if there is a quantity of more than 1 it goes into Column B.
Here is my thought process in order to remove all duplicates of items in column A and combine their totals in B:
Count the numbers of lines in column A, set as 'N'
Check all cells in column B up to 'N' and set blank cells to 1
Compare A1 to A2 thru AN, if the same combine B values and delete the line (If A1 and A2 matched, and both B cell values are 1, then A1 remains the same, B1 now has a value of 2, and the second line gets deleted.)
Repeat the loop for all values of A up to AN-1 compared to AN.
I know N will need to be reduced after each row deletion and I am pretty new to VBA so I always have trouble writing loops.
Any suggestions at pages to look at or simple structures I could use in my code would be greatly appreciated.
EDIT: Trying to turn table 1 into table 2
Table 1 ----------------------------- Table 2
Column A Column B | Column A Column B
11233 | 11233 4
11233 2 | 9987 7
9987 | 7452 1
11233 |
9987 6 |
7452 |

Sub Summator()
ActiveSheet.Columns("A:B").Sort Key1:=ActiveSheet.Range("A2"), Order1:=xlAscending, Header:=xlGuess
lastRow = Range("A65000").End(xlUp).Row
For i = 1 To lastRow
If Cells(i, 2) = "" Then Cells(i, 2) = 1
Next i
For i = lastRow To 2 Step -1
If Cells(i, 1) = Cells(i - 1, 1) Then
Cells(i - 1, 2) = Cells(i - 1, 2) + Cells(i, 2)
Cells(i, 2).EntireRow.Delete
End If
Next i
End Sub

Related

Extract excel row based on condition

Hi I have an Excel table column a below
RowNo ID CancelledBy
1 12345 Provider
2 12345 Provider
3 12345 Patient
4 12345 Patient
5 12345 Patient
6 12345 Provider
7 12345 Patient
8 12345 Provider
9 54321 Patient
10 54321 Provider
11 54321 Provider
12 54321 Patient
13 54321 Provider
From the above table I would like to pick those rows if a row contain "provider" and the immediate next row contain "Patient" then I would like to extract the two rows for that patient.
Basically "provider" rows followed by "patient" rows like the below.
RowNo ID CancelledBy
2 12345 Provider
3 12345 Patient
6 12345 Provider
7 12345 Patient
11 54321 Provider
12 54321 Patient
Is there a excel formula/vbscript or macro that will do this. I tried all day but no joy.
thanks
Edited The following might help. Data is supposed to be in sheet "MyData" (with a command button), results are written in sheet "Extracted". Code can be shortened, but I leave it hard coded for readability.
Sub Button1_Click()
Dim lLastRow As Long
Dim i As Integer
Dim k As Integer
lLastRow = Worksheets("MyData").UsedRange.Rows.Count
k = 1
For i = 1 To lLastRow
If ((Worksheets("MyData").Cells(i, 3) = "Provider" And Worksheets("MyData").Cells(i + 1, 3) = "Patient") And (Worksheets("MyData").Cells(i, 2).Value = Worksheets("MyData").Cells(i + 1, 2).Value)) Then
Worksheets("Extracted").Cells(k, 1) = Worksheets("MyData").Cells(i, 1)
Worksheets("Extracted").Cells(k, 2) = Worksheets("MyData").Cells(i, 2)
Worksheets("Extracted").Cells(k, 3) = Worksheets("MyData").Cells(i, 3)
Worksheets("Extracted").Cells(k + 1, 1) = Worksheets("MyData").Cells(i + 1, 1)
Worksheets("Extracted").Cells(k + 1, 2) = Worksheets("MyData").Cells(i + 1, 2)
Worksheets("Extracted").Cells(k + 1, 3) = Worksheets("MyData").Cells(i + 1, 3)
k = k + 2
End If
Next
End Sub
Lets say your data is in col A and B starting from row 2. use these formulas
C2 =AND(B2="Provider",B3="Patient")
Fill formula all the way down
D2 =IF(MOD(ROW(D2)-ROW($D$2),2)=0,1/AGGREGATE(14,6,1/(--($C$2:$C$14)*(ROW($C$2:$C$14))*(ROW($C$2:$C$14)>1)),1),1)
D3 =IF(MOD(ROW(D3)-ROW($D$2),2)=0,1/AGGREGATE(14,6,1/(--($C$2:$C$14)*(ROW($C$2:$C$14))*(ROW($C$2:$C$14)>D2-1)),1),D2+1)
Fill D3 down until you start getting #NUM. This populates all the row numbers that you need to get the data from.
E2 =INDEX($A$1:$B$14,D2,1)
F2 =INDEX($A$1:$B$14,D2,2)
Fill E2:F2 all the way down. This should populate your desired result.
Edit:
Revised INDEX formulas
you can try this:
if "CancelledBy" is in column C you can use this formula in D2
=IF(OR(AND(C2="provider",D1=1),AND(C2="Provider",C3="Patient")),1,0)
then copy to all rows from D3 to D14
All rows you need will be equal to 1 then you can filter column D with 1 value.
I hope this can help.
Thanks

Excel VBA - Get row of latest change in a parameter

I have a large data set which looks like this:
Employee ID |Job| Function| Level|Date of change
1 | x | a | A1 | 01/05/2014
1 | y | a | A1 | 02/04/2015
1 | y | a | A2 | 25/08/2015
1 | z | a | A3 | 27/12/2015
1 | z | c | A3 | 01/03/2016
2 | t | b | B1 | 12/05/2013
2 | v | b | B1 | 13/04/2014
2 | w | b | B3 | 12/01/2016
Each row contains a change in either job, function or level.
I need to create a table which puts together the latest change in level for each employee (so for employee 1, it would be row 4). So far I have used a combination of conditional formatting and pivots but I was wondering if there is a way to do this quicker in VBA.
Thanks!
Without VBA
This assumes that there are genuine dates in column E with format dd/mm/yyyy, In G1 enter the Array Formula:
=MAX(IF(A:A=1,E:E,""))
This gives the latest date for employee 1
Array formulas must be entered with Ctrl + Shift + Enter rather than just the Enter key.
Then in G2 enter:
=SUMPRODUCT(--(A1:A9=1)*(E1:E9=G1)*(ROW(1:9)))
This gives the row number of the record you are interested in.
From there you can use INDEX() to get any information from that row.
NOTE:
The formulas in G1 and G2 can be combined into a single cell if desired.
EDIT#1:
The same set of formulas should work with text values for the employee id as well as numbers:
Not sure this is the best solution, but since this is a one-off exercise and it did the trick I used this:
VBA to find all the rows where there was a change in level, and write a "yes" in column "F" where applicable:
Sub JLChange()
Dim Data As Worksheet
Dim i As Long
Dim lastrow As Long
Set Data = ThisWorkbook.Worksheets("Data")
lastrow = Data.Cells(Rows.Count, 1).End(xlUp).Row
For i = 1 To lastrow
If Cells(i + 1, 4).Value <> Cells(i, 4).Value And_
Cells(i + 1,1).Value = Cells(i, 1).Value Then
Cells(i + 1, 6).Value = "Yes"
Else
Cells(i + 1, 6).Value = "No"
End If
Next i
End Sub
For all the records in column "F", I used the formulas suggested by Gary's student to get the very last change.
Alternatively, you can copy-paste this database of changes in a new sheet, sort by ID and by date of change from newest to oldest, then use vlookup to get the first entry for each ID.

VBA filter result row count wrong

Language: Excel VBA
Scenario:
I have a source range (rngDTRef_AllRecord) that i need to insert the data into the destination range (rngRTDC_AllDetail)
for each of the row(rngCurrRow) in the source range (rngDTRef_AllRecord), it will filter the destination range (rngRTDC_AllDetail)
if the filter yield result, it will add some data to the result row (Note: each of the result is unique)
else it will add a new row to the destination range (rngRTDC_AllDetail)
below is the code:
For Each rngCurrRow In rngDTRef_AllRecord.Rows
intRTDC_RowBegin = 7
intRTDC_ColIdxTotal = 20
intRTDC_RowLast = fntGetNewLastRow 'this is some function get last row of rngRTDC_AllDetail due to might add in new row
Set rngRTDC_AllDetail = shtRTDC.Range(shtRTDC.Cells(intRTDC_RowBegin, 1), shtRTDC.Cells(intRTDC_RowLast, intRTDC_ColIdxTotal))
rngRTDC_AllDetail.AutoFilter
rngRTDC_AllDetail.AutoFilter Field:=intRTDC_ColIdxAcc, Criteria1:=rngCurrRow.Cells(1, intDTSource_ColIdxAccCode), Operator:=xlAnd
rngRTDC_AllDetail.AutoFilter Field:=intRTDC_ColIdxText, Criteria1:=rngCurrRow.Cells(1, strCurrAccCodeText), Operator:=xlAnd
Dim rngResult As Range
Set rngResult = rngRTDC_AllDetail.rows.SpecialCells(xlCellTypeVisible)'rngRTDC_AllDetail.SpecialCells(xlCellTypeVisible) also not work
'after filter, it will be only 1 result or none
If (rngResult.Rows.Count > 0) Then
'if the filter have result, do something here.
else
'add new row
End If
Next
My problem is after the filter, from the excelworksheet, i can see that have only 1 record, but
rngResult.Rows.Count = 2 'for the first filter record (that have 1 row only) in rngRTDC_AllDetail, i suspect due to it include the header, but i am not sure what wrong.
rngResult.Rows.Count = 1 'for the rest of the filter record that have 1 row
even worse is when there is no record after the filter, rngResult.Rows.Count = 1
Any advice will be appreciate. TQ.
Ok. After spent some time on it, I found out the solution already.
Below is some note for who facing similar problem.
Objective:
To insert "value" to columnC, when
columnA = "a" AND columnB ="b" AND the row is between 1 to 10 only
A B C
1 columnA | columnB | ColumnC
2 a | b | value
3 a | x |
4 x | x |
5 x | x |
6 c | b |
7 a | b | value
8 x | x |
9 x | x |
10 a | b | value
11 a | b |
12 a | b |
...
'insert value at columnC
ActiveSheet.Range("A1:B10").AutoFilter Field:=1, Criteria1:="a", Operator:=xlAnd
ActiveSheet.Range("A1:B10").AutoFilter Field:=2, Criteria1:="b", Operator:=xlAnd
Dim rng As Range
For Each rng In ActiveSheet.AutoFilter.Range.Range("A1:B10").SpecialCells(xlCellTypeVisible).Rows
If (rng.Row <> 1) Then 'no the header
ActiveSheet.Cells(rng.Row, "c") = "value" 'set value at C2,C7,C10
End If
Next rng
'count the total row visible
Dim rngA As Range
Set rngA = ActiveSheet.AutoFilter.Range.Range("A1:B10")
Debug.Print rngA.Columns(1).SpecialCells(xlCellTypeVisible).Count - 1 'result 3
'Reference:http://www.contextures.com/xlautofilter03.html
Note1**: "ActiveSheet.AutoFilter.Range" will always include the header and all below row as visible row.
Note2**: "ActiveSheet.AutoFilter.Range.Offset(1, 0).SpecialCells(xlCellTypeVisible).Rows" will offset the range 1 row below only, not suitable if you need to set the value at the result row.

Delete rows in which column A contains values in column A of Sheet 2

I'm traiting an 40M Excel file, I'm thinking of doing some deletes.
For example, I have the data in Sheet 1, and the primary key which I want to delete in sheet2.
Sheet 1
Column A | Column B | ...
0047 | a | ...
0048 | b | ...
0051 | c | ...
Sheet 2
Column A
0047
0051
Would you please tell me how do write a VBA script which delete line 0047 and 0051 in Sheet 1?
I'm new to VBA scripting.
try the code below. Loops through the rows until you find the values you are after using the line below you can delete rows:
Rows(i - j).Delete
Complete code:
Sub main()
Dim i As Integer
Dim j As Integer
j = 0
For i = 2 To 1000
If (Cells(i - j, 1) = "0047") Or (Cells(i - j, 1) = "0051") Then
Rows(i - j).Delete
j = j + 1
End If
Next i
End Sub

macro to re-arrange data

I have been trying to write a macro to re-arrange the Cells in the rows and columns of Stock tables for the output I desire. Luckily the Stock Tables are generally the same each and every time (Different names and values), and the desired outcome is the same format..
Here is some example Data.
A
1 Name
2 description
3 description
4 description
5 description
6 ID#: 56284
7 Quantity in stock: 34
8 Zoom In and Configure
B
1 Name
2 description
3 description
4 description
5 description
6 ID#: 56284
7 Quantity in stock: 50
8 Zoom In and Configure
And I would like the Output to go into something like this(If possible to sheet2 starting on Cell B2):
B C E
B Being Row 1
C being Row 2 3 4 and 5 Combined
E being JUST Row 7 Stock Value I.E 50
On a single spreadsheet there would be 4 columns, and 8 rows I would have to re-arrange.. Making 32 total.
It would be great to automated this, so any help would be greatly appreciated.
Let me clarify my understanding. For each column you want the following data format:
A A
1 Name 1 Name
2 Desc1 2 Desc1; Desc2; Desc3; Desc4
3 Desc2 On sheet 2 3 50
4 Desc3 --------------->
5 Desc4
6 Id#: 56284
7 Quantity in Stock: 50
8 Zoom in and configure
If this is the case you can use the following code. It assumes your data is in A1 to D8 in Sheet 1.
Sub FormatData()
Dim col As Integer
For col = 1 To 4
With Worksheets(2)
.Cells(1, col) = Cells(1, col) //Get name
.Cells(2, col) = Cells(2, col) & "; " & Cells(3, col) & "; " & Cells(4, col) & "; " & Cells(5, col) //Concatenate descriptions into single string
.Cells(3, col) = Cells(7, col) //Get quantity in stock
End With
Next col
End Sub