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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With