0

I have a table in Excel which I want to use to get some measures via SQL.

This is the first part of my code, which works fine:

Option Explicit

Sub MySQL()

    Dim cn As Object, rs As Object, output As String, sql As String

    Set cn = CreateObject("ADODB.Connection")
    With cn
        .Provider = "Microsoft.ACE.OLEDB.12.0"
        .ConnectionString = "Data Source=" & ThisWorkbook.Path & "\" & ThisWorkbook.Name & ";" & _
        "Extended Properties=""Excel 12.0 Xml;HDR=YES"";"
        .Open
    End With

Now I can get the amount of entries with a specific condition like:

sql = "SELECT COUNT(ID) FROM [Data$] WHERE [Type] = ""myType"" and [Status] = ""myStatus"""
Set rs = cn.Execute(sql)
MsgBox (rs(0))

Now I would like to use a CONTAINS condition, but this does not work:

sql = "SELECT COUNT(ID) FROM [Data$] WHERE CONTAINS([Type], ""T"")"
Set rs = cn.Execute(sql)
MsgBox (rs(0))
4
  • 1
    Did you try using LIKE ? Commented Nov 9, 2021 at 7:40
  • This returns me a 0 but at least no error: sql = "SELECT COUNT(ID) FROM [Data$] WHERE [Type] LIKE ""T""" Do I still have a Syntax issue? Commented Nov 9, 2021 at 7:56
  • 1
    You need wildcard(s) presumably e.g. %T% Commented Nov 9, 2021 at 7:59
  • wildcard=% was the hint I needed. Thanks a lot! Commented Nov 9, 2021 at 8:38

1 Answer 1

3

Contains is a non-standard SQL function that is available in SQL Server (See https://learn.microsoft.com/en-us/sql/t-sql/queries/contains-transact-sql?view=sql-server-ver15). It is used to perform fuzzy searches of all kinds.

Contains is not available when you query other data sources (Excel, Access, Oracle...).

If you just look for a substring, you can use the like-operator and use % as wildcard, eg

sql = "SELECT COUNT(ID) FROM [Data$] WHERE [Type] like '%T%' "

'%T%' will find anything containing the letter T
'T%' will find anything starting with the letter T
'%T' will find anything ending with the letter T
(this is, of course, not limited to a single character, you can use '%overflow%' if you want).

Note that different database systems have different rules for case sensitivity. Querying Excel is case insensitive, so like %t% and like %T% return the same result. This is different on other databases.

You should, btw, make it a habit to use single quotes for constant text within an SQL statement. Double quotes work in Excel but are not SQL standard and will fail in most databases.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for clarifying the question regarding CONTAINS. It works now perfectly with LIKE

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.