在 VBA 中设置范围时出现“对象变量或未设置块变量”错误
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13016776/
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
'Object variable or With block variable not set' error when setting a range in VBA
提问by David Gard
I have a function that creates a Pivot Table, but I am getting an error when I try to set a range that will be merged and have a title added to it.
我有一个创建数据透视表的函数,但是当我尝试设置将合并的范围并为其添加标题时出现错误。
In the below code, pivot_title_range
is a 'String' variable, and is optional when calling the function. title_range
is a 'Range' variable. Both lines that set the range (whether or not the users declares pivot_title_range
) cause the same error.
在下面的代码中,pivot_title_range
是一个“字符串”变量,在调用函数时是可选的。title_range
是一个“范围”变量。设置范围的两行(无论用户是否声明pivot_title_range
)都会导致相同的错误。
If pivot_title_range = "" Then
title_range = ActiveSheet.Range("B3:E4")
Else
title_range = ActiveSheet.Range(pivot_title_range)
End If
Here is the error that I am getting -
这是我得到的错误 -
Run-time error '91':
Object variable or With block variable not set
If required, here is a Pastebin of the full function - http://pastebin.com/L711jayc. The offending code starts on line 160.
如果需要,这里是完整功能的 Pastebin - http://pastebin.com/L711jayc。违规代码从第 160 行开始。
Is anybody able to tell me what I am doing wrong? Thanks.
有人能告诉我我做错了什么吗?谢谢。
回答by Jook
You need to use
你需要使用
If pivot_title_range = "" Then
Set title_range = ActiveSheet.Range("B3:E4")
Else
set title_range = ActiveSheet.Range(pivot_title_range)
End If
Because you defined title_range as range
- and this is an Object ;)
因为你定义了title_range as range
- 这是一个对象;)