Sum of First Digits
The Function
Function SFD(Range As Range) As Long
Dim vnt As Variant, i As Long, j As Long
vnt = Range
For i = 1 To UBound(vnt)
For j = 1 To UBound(vnt, 2)
If IsNumeric(vnt(i, j)) Then
If CLng(vnt(i, j)) > 0 Then SFD = SFD + CLng(Left(vnt(i, j), 1))
End If
Next
Next
End Function
In cell C9 use the formula: =SFD(B5:G5)
.
Array Version
Sub SumOfFirstDigit()
Const cRow As Long = 5
Const cCol1 As Variant = 2
Const cCol2 As Variant = 7
Const cTarget As String = "C9"
Dim j As Long
Dim sumFirst As Long
Dim vnt As Variant
vnt = Range(Cells(cRow, cCol1), Cells(cRow, cCol2))
For j = 1 To UBound(vnt, 2)
If IsNumeric(vnt(1, j)) Then
If CLng(vnt(1, j)) > 0 Then _
sumFirst = sumFirst + CLng(Left(vnt(1, j), 1))
End If
Next
Range(cTarget).Value = sumFirst
End Sub
Range Version
Sub SumOfFirstDigit2()
Const cRow As Long = 5
Const cCol1 As Variant = 2
Const cCol2 As Variant = 7
Const cTarget As String = "C9"
Dim j As Long
Dim sumFirst As Long
For j = cCol1 To cCol2
If IsNumeric(Cells(cRow, j)) Then
If Cells(cRow, j) > 0 Then _
sumFirst = sumFirst + CLng(Left(Cells(cRow, j), 1))
End If
Next
Range(cTarget).Value = sumFirst
End Sub
Quick Repair
- You forgot
Dim cellref As Range
.
- You forgot
Set
in Set cellref = Cells(5, colnum)
.
- You misspelled
celref
in sumfirst = sumfirst + (Left(cellref, 1))
.
- You forgot
Set cellref = Nothing
Integer
is dead, Long
prevails.
The Code
Sub sum_first_digit()
Dim cellref As Range
Dim colnum As Long
Dim sumfirst As Long
sumfirst = 0
For colnum = 2 To 7
Set cellref = Cells(5, colnum)
sumfirst = sumfirst + (Left(cellref, 1))
Next colnum
Range("C9").Value = sumfirst
Set cellref = Nothing
End Sub