For work, I'm trying to set up a macro to sum all the values in a column based on a specific column header using VBA. (The location of the columns can change.)
For example, I'm trying find the column with header "Blueberry" and sum all the values in the column and return value in E2 (see sample xls below).
I tried both methods below, but failed. What am I missing? Learning VBA and need some help for work! Any insights and pointers would be appreciated!
Version 1
Version 2
For example, I'm trying find the column with header "Blueberry" and sum all the values in the column and return value in E2 (see sample xls below).
I tried both methods below, but failed. What am I missing? Learning VBA and need some help for work! Any insights and pointers would be appreciated!
Version 1
VBA Code:
Sub sumRange()
Dim colHeaders As Range
Dim colID As Long
Set colHeaders = Range("1:1")
colID = Application.Match("Blueberry", colHeaders, 0)
If Not IsError(colID) Then
Range("E2") = Application.WorksheetFunction.Sum(Range("colID":"colID"))
End If
End Sub
Version 2
VBA Code:
Sub sumRange()
Dim rngS As Range
Set rngS = Range(Cells(1, 1), Cells(1, _
Cells(1, Columns.Count).End(xlToLeft).Column)).Find("Blueberry")
If Not rngS Is Nothing Then
Range("E2") = Application.WorksheetFunction.Sum(rngS)
End If
End Sub
Apple | Orange | Banana | Blueberry | Total Banana | |
---|---|---|---|---|---|
123 | 342 | 234 | 4 | ||
23123 | 3423 | 234 | 4 | ||
3423 | 234 | 234 | 32 | ||
423432 | 24 | 24 | 4342 |