Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Object variable or With block variable not set when returning from function

Tags:

excel

vba

Why am I receiving an Object variable or With block variable not set error with the following code:

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.

I get the error at the GetConnection = cn line.

like image 858
Nightwolf Avatar asked Dec 27 '22 09:12

Nightwolf


1 Answers

If memory serves me right... you need to use the 'set' keyword when working with reference types (objects) in classic vb

ie:

Set GetConnection = cn

This applies to all assignments, not just function return statements.

like image 200
Mike Gasparelli Avatar answered May 14 '23 15:05

Mike Gasparelli