I'm attempting to write a simple VBA macro that will take the active cell's column and the user's input to add a range of cells on a single row together. The range is calculated by adding the integer the user inputs to the active column and that is the end column. The problem is it gives me Run-time error '424' and tells me "Object required". When I run it, and gets angry at the sum line.
Here is my code. I'm just starting in VBA so it can't be that hard....right?
Sub Food()
Dim first As Variant
Dim last As Integer
Dim days As Integer
Dim month As Variant
Dim total As Double
first = ActiveCell.Column
days = InputBox("Days in the month?")
last = first + days
month = Range(Cells(first, 4), Cells(last, 4))
total = Excel.WorksheetFunction.Sum(Report.Range(month))
Worksheets(1).Cells(1, 13).Value = total
End Sub
Answer
The error is the way you are trying to sum the range. Try like this:
total = WorksheetFunction.Sum(month)
Whenever you see a problem in VBA, try to isolate it an resolve it separately. E.g., in your case something like this would have helped, as an isolation example:
Option Explicit
Sub TestMe()
Dim rngRange As Range
Set rngRange = Range("A1:A5")
'Any of these is ok:
Debug.Print WorksheetFunction.Sum(rngRange)
Debug.Print WorksheetFunction.Sum(Range("A1:A5"))
Debug.Print WorksheetFunction.Sum(1, 2, 3)
Debug.Print WorksheetFunction.Sum(Array(1, 2, 3))
Debug.Print WorksheetFunction.Sum(Array(1, 1, 545), Array(-2))
End Sub
No comments:
Post a Comment