vba 从函数返回时未设置对象变量或带块变量
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14847008/
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 when returning from function
提问by Nightwolf
Why am I receiving an Object variable or With block variable not seterror with the following code:
为什么我收到一个Object 变量或 With block variable not set错误,代码如下:
Function GetConnection() As ADODB.Connection
'Create connection to worksheet
Dim cn As ADODB.Connection
Set cn = New ADODB.Connection
cn.Provider = "Microsoft.Jet.OLEDB.4.0"
cn.ConnectionString = "Data Source=" & ThisWorkbook.FullName & ";" & "Extended Properties=Excel 8.0;"
cn.Open
GetConnection = cn
End Function
I've declared the object as 'cn', initialized it properly, and am then setting some properties and opening it, before returning it.
我已经将对象声明为“cn”,正确初始化它,然后设置一些属性并打开它,然后返回它。
I get the error at the GetConnection = cn line.
我在 GetConnection = cn 行收到错误消息。
回答by Mike Gasparelli
If memory serves me right... you need to use the 'set' keyword when working with reference types (objects) in classic vb
如果我没记错的话……在经典 vb 中使用引用类型(对象)时,您需要使用“set”关键字
ie:
IE:
Set GetConnection = cn
This applies to all assignments, not just function return statements.
这适用于所有赋值,而不仅仅是函数返回语句。