VBA范围功能/变量对象错误

时间:2018-07-09 01:48:05

标签: vba excel-vba excel

我不知道为什么在调用具有所需范围/变量的函数时,在VBA中始终出现对象错误。我想从B8,B9,B10中的子/目标/目标单元格(作为范围)rng调用SumSameCells函数

任何帮助将不胜感激。谢谢

Sub MySums()

Call SumSameCells(B8)
Call SumSameCells(B9)
Call SumSameCells(B10)

End Sub

Function SumSameCells(rng As Range)

    x = 0
    For i = 2 To 3
        x = x + Sheets(i).Range(" & rng.Address & ")
    Next i
    Sheet1.Range(" & rng.Address & ") = x

End Function

2 个答案:

答案 0 :(得分:0)

此:

Call SumSameCells(B8)

没有传递范围B8,而是一个未声明的变量B8

使用Option Explicit会警告您这种错误。

这会更简单:

Sub MySums()

SumSameCells "B8"
SumSameCells "B9"
SumSameCells "B10"

End Sub

Function SumSameCells(addr As String)

    x = 0
    For i = 2 To 3
        x = x + Sheets(i).Range(addr).Value
    Next i
    Sheet1.Range(addr) = x

End Function

答案 1 :(得分:0)

已给出答案的变化。

  1. 函数返回一些信息。您正在使用返回值,因此请将其作为子值。
  2. 在这种情况下不需要循环。您可以直接求和。
  3. 为x声明适当的类型。 Option Explicit已经被提及。
  4. 使用工作表集合以避免尝试使用图表表。
  5. 按旧删除call关键字。

代码:

Option Explicit
Public Sub MySums()
    SumSameCells "B8"
    SumSameCells "B9"
    SumSameCells "B10"
End Sub

Public Sub SumSameCells(ByVal addr As String)
  Dim x As Double '<== Use whatever appropriate type is
  x = Application.WorksheetFunction.Sum(Worksheets(2).Range(addr), Worksheets(3).Range(addr))
  Worksheets("Sheet1").Range(addr) = x
End Sub
相关问题