theObserver
New Member
- Joined
- Nov 28, 2013
- Messages
- 5
I have an annoying problem with SQL in VBA. I've setup a ADODB.Connection to run sql against a worksheet using referenced cells :-
Public Function OpenExcelDatabase() As ADODB.Connection
Dim sTemp As String
Set cn = New ADODB.Connection
If Val(Application.Version) < 12 Then 'Excel 97-2003
sTemp = "Provider=Microsoft.Jet.OLEDB.4.0;"
Else 'Excel 2007-2010
sTemp = "Provider=Microsoft.ACE.OLEDB.12.0;"
End If
sTemp = sTemp & "Data Source=" & ThisWorkbook.FullName & ";" & "Extended Properties='Excel 8.0;HDR=yes;IMEX=1'"
cn.ConnectionString = sTemp
cn.Open
Set OpenExcelDatabase = cn
End Function
Problem is, things work fine when my where clause contains a number. But when I change it to a letter, I get a 'no value given for one or more requirement parameters' or 'automation error' :
Set DBConnection = OpenExcelDatabase
Set rngSource = Sheets("Mastercard CMTC Combinations").Columns("E")
sWorksheet = "[" & rngSource.Parent.Name & "$]"
sSql = ""
sSql = sSql & " " & "SELECT DISTINCT [CAM]"
sSql = sSql & " " & "FROM " & sWorksheet
sSql = sSql & " " & "WHERE [CIC] = B"
MsgBox (sSql)
PopulateControl cmbCM1, sSql, DBConnection
****
Public Sub PopulateControl(Ctrl As ComboBox, sSql As String, ByVal cn As ADODB.Connection)
Dim rs As ADODB.Recordset
Set rs = New ADODB.Recordset
Set rs = cn.Execute(sSql)
....
***
If I change the 'B' in the where clause to a '2', things work fine. The column [CIC] contains 2s, Bs etc.
Any idea what could be causing the problem? I've tried "WHERE [CIC] = B" and "WHERE [CIC] = 'B' "
Public Function OpenExcelDatabase() As ADODB.Connection
Dim sTemp As String
Set cn = New ADODB.Connection
If Val(Application.Version) < 12 Then 'Excel 97-2003
sTemp = "Provider=Microsoft.Jet.OLEDB.4.0;"
Else 'Excel 2007-2010
sTemp = "Provider=Microsoft.ACE.OLEDB.12.0;"
End If
sTemp = sTemp & "Data Source=" & ThisWorkbook.FullName & ";" & "Extended Properties='Excel 8.0;HDR=yes;IMEX=1'"
cn.ConnectionString = sTemp
cn.Open
Set OpenExcelDatabase = cn
End Function
Problem is, things work fine when my where clause contains a number. But when I change it to a letter, I get a 'no value given for one or more requirement parameters' or 'automation error' :
Set DBConnection = OpenExcelDatabase
Set rngSource = Sheets("Mastercard CMTC Combinations").Columns("E")
sWorksheet = "[" & rngSource.Parent.Name & "$]"
sSql = ""
sSql = sSql & " " & "SELECT DISTINCT [CAM]"
sSql = sSql & " " & "FROM " & sWorksheet
sSql = sSql & " " & "WHERE [CIC] = B"
MsgBox (sSql)
PopulateControl cmbCM1, sSql, DBConnection
****
Public Sub PopulateControl(Ctrl As ComboBox, sSql As String, ByVal cn As ADODB.Connection)
Dim rs As ADODB.Recordset
Set rs = New ADODB.Recordset
Set rs = cn.Execute(sSql)
....
***
If I change the 'B' in the where clause to a '2', things work fine. The column [CIC] contains 2s, Bs etc.
Any idea what could be causing the problem? I've tried "WHERE [CIC] = B" and "WHERE [CIC] = 'B' "