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

Create a Pivot Table on a Map
If your data has zip codes, postal codes, or city names, select the data and use Insert, 3D Map. (Found to right of chart icons).

Forum statistics

Threads
1,223,908
Messages
6,175,304
Members
452,633
Latest member
DougMo

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