5

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.

1 Answer 1

12

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Perfect, that worked, thank you! I'm a little embarrassed I couldn't figure that out on my own.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.