I am having a problem with the code below. Basically, I want to populate a combo box with Access data by sending the combobox object and a SQL string to a subroutine. My problem is that it works when I use a simple query like: "SELECT * FROM tblname;", but anything more complicated than that fails with the error "Method 'Execute' of object '_Connection' Failed"
Any ideas why this is happening?
CODE
Sub Populate_Combobox_Recordset(ByRef objCBO As ComboBox, sSQL As String)
Dim cnt As ADODB.Connection
Dim rst As ADODB.Recordset
Dim stDB As String, stConn As String, stSQL As String
Dim xlCalc As XlCalculation
Dim vaData As Variant
Dim k As Long
'In order to increase the performance.
With Application
xlCalc = .Calculation
.Calculation = xlCalculationManual
.EnableEvents = False
.ScreenUpdating = False
End With
'Instantiate the Connectionobject.
Set cnt = New ADODB.Connection
'Path to and the name of the database.
stDB = GBL_DatabasePath
'Create the connectionstring.
stConn = "Provider=Microsoft.Jet.OLEDB.4.0;" & _
"Data Source=" & stDB & ";"
'==================================
sSQL = "SELECT * FROM sp83_zones;" 'This works
sSQL = "SELECT [Zone] & " - " & [Description] AS [Text], utm_zones.Zone FROM utm_zones;" 'This doesn't work
'==============================
With cnt
.CursorLocation = adUseClient 'Necesary for creating disconnected recordset.
.Open stConn 'Open connection.
'Instantiate the Recordsetobject and execute the SQL-state.
'This is where it fails: =================================
Set rst = .Execute(sSQL)
'==============================================
End With
With rst
Set .ActiveConnection = Nothing 'Disconnect the recordset.
k = .Fields.Count
'Populate the array with the whole recordset.
vaData = .GetRows
End With
'Close the connection.
cnt.Close
With objCBO
.Clear
.BoundColumn = k
.List = Application.Transpose(vaData)
.ListIndex = -1
.ColumnCount = 1
End With
'Restore the settings.
With Application
.Calculation = xlCalc
.EnableEvents = True
.ScreenUpdating = True
End With
'Release objects from memory.
Set rst = Nothing
Set cnt = Nothing
End Sub