vba 将范围变量传递给 Excel 宏中的公式

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10811719/
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-11 16:20:00  来源:igfitidea点击:

Passing Range Variable into formula in Excel Macro

excelexcel-vbaexcel-2007vba

提问by BiGXERO

Im trying to use variables in macro formulas to avoid selecting cells, however i keep getting an error.

我试图在宏公式中使用变量来避免选择单元格,但是我不断收到错误消息。

Here is a simplification of what im trying to do:

这是我尝试做的事情的简化:

    Dim myRange as Range
    Dim formulaCell as Range

    Set myRange = [a1:a10]
    formulaCell.Formula = "=sum(myRange)"

However i keep getting:

但是我不断得到:

"application-defined or object defined error"

I have tried using:

我试过使用:

formulaCell.Formula = "=sum(" & myRange & ")"

but then i get:

但后来我得到:

Type mismatch

Also tried:

还试过:

formulaCell.Formula = "=sum(" & Range(myRange) & ")"

to no avail

无济于事

Im sure the answer is very basic but cannot work out what i am doing wrong. Any and all help would be greatly appreciated.

我确定答案非常基本,但无法弄清楚我做错了什么。任何和所有的帮助将不胜感激。

回答by KopBuH

At first you must set value to formulaCell. Then use next string instead of yours

首先,您必须将 value 设置为formulaCell。然后使用下一个字符串而不是你的

formulaCell.Formula = "=sum(" + myRange.Address + ")"