我尝试编写一个简单的VBA宏,它将使用活动单元格的列和用户的输入在一行中添加一系列单元格。通过将用户输入的整数添加到活动列并且即结束列来计算范围。问题是它给了我运行时错误''''告诉我"对象需要"。当我跑它,并在总和线上生气。
这是我的代码。我刚从VBA开始,所以它不会那么难......对吗?
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
答案 0 :(得分:0)
错误是您尝试对范围求和的方式。试试这样:
total = WorksheetFunction.Sum(month)
每当您在VBA中发现问题时,请尝试将其隔离并单独解决。例如,在你的情况下,这样的事情会有所帮助,作为一个孤立的例子:
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