Connect to spreadsheet Help

Molden

Active Member
Joined
Jun 20, 2006
Messages
373
Hi All,

I have reperative code which I am trying to sort but can't seem to crack it.

What I am trying to do is put SQL in a sub and then make it connect to a seperate excel sheet.

At the minute I have to put the connect code in each module so is in about 5 times.

Is there anyway to just have the connecting code to the spread sheet in one module and the SQL in another?

This is what I have

Code:
Sub LoadCategoriesUserform()

Dim rstRecordset As ADODB.Recordset

    Dim strSQL As String

    strSQL = "SELECT * FROM [Sheet1$] WHERE [Category] <> '0' ORDER BY 1"
       
    Set rstRecordset = ExecuteSQLGetRS(strSQL)
    
    Do While Not rstRecordset
        UserForm1.ComboBox1.AddItem rs.Fields(0)
        rs.MoveNext
    Loop
        
    rs.Close
    cn.Close
    Set cn = Nothing

End Sub

Code:
Public Function ExecuteSQLGetRS(ByVal strSQL As String) As ADODB.Recordset

    Set cn = CreateObject("ADODB.Connection")
    Set rs = CreateObject("ADODB.Recordset")

    With cn
        
        .Provider = "Microsoft.ace.OLEDB.12.0"
        .ConnectionString = "Data Source=" & MyExcelFile & ";" & _
        "Extended Properties=Excel 12.0"
        .Open
        
    End With
 
    rs.Open strSQL, cn
    
    Set ExecuteSQLGetRS = rs

End Function

Any help would be great

Thank you
 
Last edited:

Excel Facts

Waterfall charts in Excel?
Office 365 customers have access to Waterfall charts since late 2016. They were added to Excel 2019.

Forum statistics

Threads
1,215,777
Messages
6,126,832
Members
449,343
Latest member
DEWS2031

We've detected that you are using an adblocker.

We have a great community of people providing Excel help here, but the hosting costs are enormous. You can help keep this site running by allowing ads on MrExcel.com.
Allow Ads at MrExcel

Which adblocker are you using?

Disable AdBlock

Follow these easy steps to disable AdBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the icon in the browser’s toolbar.
2)Click on the "Pause on this site" option.
Go back

Disable AdBlock Plus

Follow these easy steps to disable AdBlock Plus

1)Click on the icon in the browser’s toolbar.
2)Click on the toggle to disable it for "mrexcel.com".
Go back

Disable uBlock Origin

Follow these easy steps to disable uBlock Origin

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back

Disable uBlock

Follow these easy steps to disable uBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back
Back
Top