noslenwerd
Board Regular
- Joined
- Nov 12, 2019
- Messages
- 85
- Office Version
- 365
I think I am close with my code below, but it doesn't function quite as flawlessly.
What I am trying to achieve is:
The issue is, it does add the missing values to Sheet2, but at times it doesn't add +1 to column B correctly.
Any ideas?
What I am trying to achieve is:
- Check to see if cell in Sheet1 range (found in column A), exists in Sheet2 column A.
- If cell exists in Sheet2, +1 to the value in column B
- If cell DOES NOT exist in Sheet2, copy that cell to the end of Sheet2 columnA, and +1 to the value in columnB
VBA Code:
Sub UpdateCount()
Dim sh1 As Worksheet, sh2 As Worksheet, lr As Long, rng As Range
Set sh1 = Sheets(1)
Set sh2 = Sheets(2)
lr = sh1.Cells(Rows.Count, 1).End(xlUp).Row 'find last row
Set rng = sh1.Range("A2:A" & lr) 'set range to all non-blank cells in Sheet1 Column A
For Each c In rng 'Run through each cell in rng
If WorksheetFunction.CountIf(sh2.Range("A:A"), c.Value) = WorksheetFunction.CountIf(sh1.Range("A:A"), c.Value) Then 'If cell in Sheet1, matches a value in Sheet2, add 1 to value in Column B
sh2.Range("A" & (c.Row)).Offset(, 1).Value = sh2.Range("A" & (c.Row)).Offset(, 1).Value + 1 'This is where I believe something is wrong with the code
End If
If WorksheetFunction.CountIf(sh2.Range("A:A"), c.Value) = 0 Then 'If cell from Sheet1, is not in Sheet2, copy to Sheet2, and add +1 to column B
sh2.Range("A" & sh2.Cells(Rows.Count, 1).End(xlUp).Row)(2) = c.Value
sh2.Range("A" & sh2.Cells(Rows.Count, 1).End(xlUp).Row).Offset(, 1).Value = sh2.Range("A" & sh2.Cells(Rows.Count, 1).End(xlUp).Row).Offset(, 1).Value + 1
End If
Next
End Sub
The issue is, it does add the missing values to Sheet2, but at times it doesn't add +1 to column B correctly.
Any ideas?