VBA 对一系列单元格求和

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/45488027/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-08 10:53:49  来源:igfitidea点击:

VBA Sum a Range of Cells

excelvbaexcel-vbasumrange

提问by Josh

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.

我正在尝试编写一个简单的 VBA 宏,它将采用活动单元格的列和用户的输入将一系列单元格添加到一行中。该范围是通过将用户输入的整数添加到活动列(即结束列)来计算的。问题是它给了我运行时错误“424”并告诉我“需要对象”。当我运行它时,对总和线感到生气。

Here is my code. I'm just starting in VBA so it can't be that hard....right?

这是我的代码。我刚刚开始使用 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

采纳答案by Vityata

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:

每当您在 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