简体   繁体   中英

Use of Like * Works in MS-Access but Not VBA

I have a simple query but am running into problems using LIKE in VBA. My SQL string in VBA is:

stsql1 = "Select Top 25 data.* from data where data.Description Like ('*') "

When I run this sql string in my VBA code I get no records returned, but if I copy/paste the same string into a query in SQL View in MS Access, the query returns the values I expect. Is there a trick to using the "Like" syntax in VBA?

I can provide additional code and a small version of the database if that would help.

For SQL, the database engine will accept either single or double quotes as text delimiters. So either of these 2 WHERE clauses will work.

WHERE some_field Like '*'
WHERE some_field Like "*"

VBA however only accepts double quotes as text delimiters, so you would have to use the second form.

Two other points about your SELECT statement:

Select Top 25 data.* from data where data.Description Like ('*')
  1. TOP [number] is arbitrary without an ORDER BY clause
  2. You don't need parentheses surrounding your Like pattern ... you can use Like "*"

If your VBA code is using ADO with that SELECT statement, you must change the wild card character from * to % ...

WHERE data.Description Like '%'

In ADO/VBA, you have to use % instead of * as the wildcard. I ran into this a couple times in the past ....

I can't add a comment, but I think it would be worth noting that you have to use % even if you are querying MS Access.

(example: Outlook VBA runs query on an Access database. The proper query is select * where user like '%bob%' , even though this query would not work if plugged directly into an MS Access query).

Realize that there are at least 2 (yes two!) LIKE operators here.

One is the LIKE operator of VBA.

The other is the LIKE operator of the SQL of the database you are attached to.

The usual wildcards in SQL are % (for any # of any characters) and _ (for one of any character).

Know also that MS Access can open databases that aren't Access; it could be Microsoft SQL Server, or Oracle or IBM DB2. (BTW, the database that is normal for Access is called Microsoft JET.) You may be sheltered from that truth when you create a Query object in Access - in that circumstance, you are using JET SQL even when it's a linked table you are querying.

However, under VBA, when using either DAO or ADO, you're talking directly to whatever the database system happens to be, in which case you MUST use the SQL of that specific system.

OK, short answer: Use % like cularis said.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM