我不知道为什么在调用具有所需范围/变量的函数时,在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
答案 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)
已给出答案的变化。
Option Explicit
已经被提及。代码:
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