excel vba code to find duplicates in a column and add their corresponding values from another column

5
Excel VBA code to find duplicates in a column and add their corresponding values from another column up vote0do wn vot efavo rite I hope someone will be able to help me with this. I have a column A with staff id's and have their hours worked in another column K. There are some staff id's that appear more than once on the list and I would like to know if there is a way in Excel VBA with which I can check if each of the staff id's appears more than once, a nd if so, then add up their total hours worked and put the result in another column corresponding to the first instance of that st aff id and the duplicates being 0. This is for a monthly report and there may be over 2k records at any point. Any help will be appreciated. Thanks in advance PS - I am just an intermediate when it comes to VBA. 3 did you try anything?? do you really need to do it with VBA as a pivot table could be good enough to KazJaw Mar 14 at 16:31 1 indeed use a pivot table, problem solved I guess...  K_B Mar 14 at 16:34 exactly, use a pivot table to group and sum your data...  Philip Mar 14 at 16:51 1 The reason I want to use VBA is because this is one part of the entire process, which is in place and i report is run monthly and is calculated using VBA, and the aim is to minimise manual intervention a Thanks for the suggestions though.  user2170214 Mar 14 at 16:53 1 another alternative in Excel VBA is to use the worksheet functions COUNTIF and SUMIF in your VBA (Application.WorksheetFunction.SumIf) if you write some code, we'll help you fix it   Philip Mar show 3 more comments 3 Answers activeoldest votes up vote1do wn vote As everyone else said, a Pivot Table really is the best way. If you're unsure how to use a PivotTable or what it's good for, refer to this SO post where I explain in detail. Anyway, I put together the below VBA function to he lp get you started. It's by no means the most efficient approach; it also makes the following assumptions:  Sheet 1 has all the data  A has Staff Id  B has Hours  C is reserved for Total Hours  D will be available for processing status output 

Upload: nazirsayyed

Post on 10-Feb-2018

221 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: Excel VBA Code to Find Duplicates in a Column and Add Their Corresponding Values From Another Column

7/22/2019 Excel VBA Code to Find Duplicates in a Column and Add Their Corresponding Values From Another Column

http://slidepdf.com/reader/full/excel-vba-code-to-find-duplicates-in-a-column-and-add-their-corresponding-values 1/5

Excel VBA code to find duplicates in a column and add their corresponding values from another

column

up

vote0do

wn

vot efavo

rite 

I hope someone will be able to help me with this. I have a column A with staff id's and have their

hours worked in another column K. There are some staff id's that appear more than once on the

list and I would like to know if there is a way in Excel VBA with which I can check if each of the

staff id's appears more than once, and if so, then add up their total hours worked and put the

result in another column corresponding to the first instance of that staff id and the duplicatesbeing 0.

This is for a monthly report and there may be over 2k records at any point.

Any help will be appreciated.

Thanks in advance

PS - I am just an intermediate when it comes to VBA.

did you try anything?? do you really need to do it with VBA as a pivot table could be good eno

KazJaw Mar 14 at 16:31 

1 indeed use a pivot table, problem solved I guess... – K_B Mar 14 at 16:34 

exactly, use a pivot table to group and sum your data... – Philip Mar 14 at 16:51 

The reason I want to use VBA is because this is one part of the entire process, which is in plac

report is run monthly and is calculated using VBA, and the aim is to minimise manual interve

Thanks for the suggestions though. – user2170214 Mar 14 at 16:53 

another alternative in Excel VBA is to use the worksheet functions COUNTIF and SUMIF in yo

(Application.WorksheetFunction.SumIf) if you write some code, we'll help you fix it  – Phili

show 3 more comments

3 Answers

activeoldest votes

up

vote1do

wn vote

As everyone else said, a Pivot Table really is the best way. If you're unsure how to use a

PivotTable or what it's good for, refer to this SO post where I explain in detail. Anyway, I put together the below VBA function to help get you started. It's by no means the most 

efficient approach; it also makes the following assumptions:

  Sheet 1 has all the data

  A has Staff Id

  B has Hours

  C is reserved for Total Hours

  D will be available for processing status output 

Page 2: Excel VBA Code to Find Duplicates in a Column and Add Their Corresponding Values From Another Column

7/22/2019 Excel VBA Code to Find Duplicates in a Column and Add Their Corresponding Values From Another Column

http://slidepdf.com/reader/full/excel-vba-code-to-find-duplicates-in-a-column-and-add-their-corresponding-values 2/5

This of course can all be changed very easily by altering the code a bit. Review the code, it's

commented for you to understand.

The reason a Status column must exist is to avoid processing a Staff Id that was already

processed. You could very alter the code to avoid the need for this column, but this is the way I

went about things.

CODE 

Public Sub HoursForEmployeeById()

Dim currentStaffId As String 

Dim totalHours As Double 

Dim totalStaffRows As Integer 

Dim currentStaffRow As Integer 

Dim totalSearchRows As Integer 

Dim currentSearchRow As Integer 

Dim staffColumn As Integer 

Dim hoursColumn As Integer 

Dim totalHoursColumn As Integer 

Dim statusColumn As Integer 

'change these to appropriate columns 

staffColumn = 1 

hoursColumn = 2 

totalHoursColumn = 3 

statusColumn = 4 

Application.Calculation = xlCalculationManual

Application.ScreenUpdating = False 

totalStaffRows = Sheet1.Cells(Rows.Count, staffColumn).End(xlUp).Row

For currentStaffRow = 2 To totalStaffRows

currentStaffId = Cells(currentStaffRow, staffColumn).Value

'if the current staff Id was not already processed (duplicate record) 

If  Not StrComp("Duplicate", Cells(currentStaffRow, statusColumn).Value, vbTextCompare) = 0

Then 

'get this rows total hours 

totalHours = CDbl(Cells(currentStaffRow, hoursColumn).Value)

'search all subsequent rows for duplicates 

totalSearchRows = totalStaffRows - currentStaffRow + 1 

Page 3: Excel VBA Code to Find Duplicates in a Column and Add Their Corresponding Values From Another Column

7/22/2019 Excel VBA Code to Find Duplicates in a Column and Add Their Corresponding Values From Another Column

http://slidepdf.com/reader/full/excel-vba-code-to-find-duplicates-in-a-column-and-add-their-corresponding-values 3/5

  For currentSearchRow = currentStaffRow + 1 To totalSearchRows

If StrComp(currentStaffId, Cells(currentSearchRow, staffColumn), vbTextCompare) = 0 

Then 

'duplicate found: log the hours worked, set them to 0, then mark as Duplicate 

totalHours = totalHours + CDbl(Cells(currentSearchRow, hoursColumn).Value)

Cells(currentSearchRow, hoursColumn).Value = 0 

Cells(currentSearchRow, statusColumn).Value = "Duplicate" End If  

Next  

'output total hours worked and mark as Processed 

Cells(currentStaffRow, totalHoursColumn).Value = totalHours

Cells(currentStaffRow, statusColumn).Value = "Processed" 

totalHours = 0  'reset total hours worked 

End If  

Next  

Application.ScreenUpdating = False 

Application.Calculation = xlCalculationAutomatic

End Sub 

BEFORE 

 AFTER 

Page 4: Excel VBA Code to Find Duplicates in a Column and Add Their Corresponding Values From Another Column

7/22/2019 Excel VBA Code to Find Duplicates in a Column and Add Their Corresponding Values From Another Column

http://slidepdf.com/reader/full/excel-vba-code-to-find-duplicates-in-a-column-and-add-their-corresponding-values 4/5

 

456 should result with 30 in line 3... – KazJaw Mar 14 at 17:43 

ah...crap. Looks like a good exercise then for the OP ;) This is untested and as-is, it should serve a

though. Thanks for catching that. I unfortunately don't have time to debug right now. – SamMar 1 

up

vote0do

wn vote

Here is the solution for the data table located in range A1:B10 with headers and results written to

column C.

Sub Solution()

Range("c2:c10").Clear

Dim i

For i = 2 To 10 

If WorksheetFunction.SumIf(Range("A1:a10"), Cells(i, 1), Range("C1:C10")) = 0 Then 

Cells(i, "c") = WorksheetFunction.SumIf( _

Range("A1:a10"), Cells(i, 1), Range("B1:B10"))

Else 

Cells(i, "c") = 0 

End If  

Next i

End Sub 

Kaz Jaw & @Sam, thank you for the suggestions and help. I have tweaked your codes slightly, as r

giving the desired result. Your inputs have been very valuable. – user2170214 Mar 15 at 11:16 

Try below code :

Sub sample()

Dim lastRow As Integer, num As Integer, i As Integer 

lastRow = Range("A65000").End(xlUp).Row

Page 5: Excel VBA Code to Find Duplicates in a Column and Add Their Corresponding Values From Another Column

7/22/2019 Excel VBA Code to Find Duplicates in a Column and Add Their Corresponding Values From Another Column

http://slidepdf.com/reader/full/excel-vba-code-to-find-duplicates-in-a-column-and-add-their-corresponding-values 5/5

  For i = 2 To lastRow

num = WorksheetFunction.Match(Cells(i, 1), Range("A1:A" & lastRow), 0)

If i = num Then 

Cells(i, 3) = WorksheetFunction.SumIf(Range("A1:A" & lastRow), Cells(i, 1), Range("B1:B" &

lastRow))

Else Cells(i, 1).Interior.Color = vbYellow

End If  

Next  

End Sub 

BEFORE

AFTER

share|improve this answer