Macro not sum empty cells and show results in other sheet vertically

1

1234

Hi,

I have this macro that sums all the values of each code like this:

J R
PL 32 10
PL 22 5
PL 32 3

And it sums

PL 32 = 13
PL 22=5

But from left to right and it sums also empty cells?

How can I make this macro not sum the empty cells and if possible that
it shows the J results in Sheet2 A35 and in Sheet2 B35 the sum of J
values vertically?

Sub Total_by_code()
Const CodeCol = "J" 'Columna con código repetido
Const ValueCol = "R" 'Column con los valores de cada código
Const StotalCol = "T" 'Column donde se sumará cada valor
Dim CodeRng As Range, ValueRng As Range, StotalRng As Range
Dim StotalCell As Range, NextCell As Range, rng As Range
Dim startrow As Long, lastrow As Long
Dim Col As Variant, ncol As Long
startrow = 1 'numero de fila en donde estará el primer valor de la
clumna
lastrow = Cells(Rows.Count, CodeCol).End(xlUp).Row
Set CodeRng = Range(Cells(startrow, CodeCol), Cells(lastrow,
CodeCol))
Set ValueRng = Range(Cells(startrow, ValueCol), _
Cells(lastrow, ValueCol))
Set StotalRng = Range(Cells(startrow, StotalCol), _
Cells(startrow, Columns.Count))
Set StotalCell = Cells(startrow, StotalCol)
StotalRng.Resize(2).ClearContents
For Each rng In CodeRng
If StotalCell = "" Then
StotalCell = rng.Value
StotalCell.Offset(1, 0).Formula = "=sumif(" & _
CodeRng.Address(False, False) & ",""" & rng.Value & _
"""," & ValueRng.Address(False, False) & ")"
Set NextCell = StotalCell.Offset(0, 1)
Else
Col = Application.Match(rng.Value, StotalRng, 0)
If IsError(Col) Then Col = 0
If Col > 0 Then
StotalCell.Offset(0, Col - 1) = rng.Value
StotalCell.Offset(1, Col - 1).Formula = "=sumif(" & _
CodeRng.Address(False, False) & ",""" & rng.Value & _
"""," & ValueRng.Address(False, False) & ")"
Else
NextCell = rng.Value
NextCell.Offset(1, 0).Formula = "=sumif(" & _
CodeRng.Address(False, False) & ",""" & rng.Value & _
"""," & ValueRng.Address(False, False) & ")"
Set NextCell = NextCell.Offset(0, 1)
End If
End If
Next
End Sub

Thanks!!
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top