Skip to content
Advertisement

Nested SQL Select query in Excel with VBA

I’m trying to make SQL query on multiple Excel worksheets.

I have setup like this (each table is a separate worksheet): enter image description here

Three worksheets – one with condition, second with source data and third with the output.

In the Output I need all records from the Source where value in the ColumnA is present in the Condition next to a positive number.

I was trying to do something like this:

First problem occurred because of blank values in the Condition table. It can not handle number comparison if there are blank values in that column – Data type mismatch in criteria expression. For now I dealt with it by doing this ugly thing: Where Column2 <> '' And Column2 <> '0'

But that’s not the main question. I have bigger problem and it is has something to do with nesting one Select inside another. Even though inner Select returns single column with values like this:

enter image description here

I’m still getting error Type mismatch in criteria expression. (slightly different error than above).

So I can run inner expression just fine. I can run outer expression with hard coded values also just fine (for example Where ColumnA In "'value1','value2',..."). But when I’m nesting them I’m getting the error. To my SQL knowledge I think this query should work, but for some reason inner query in excel returns data that is not compatible with in operator.

This is my full code (thanks to this SO answer):

Advertisement

Answer

Possibly the NumberFormat of Column2 in Condition sheet is set to General or Text. Try re-formatting entire column (not subset range) as Number and then save changes so SQL engine recognizes the data type as number. From there, you can run your SQL query with IN clause or better yet, use INNER JOIN:

Additionally, consider the Excel ODBC driver that handles any format (.xls, .xlsx, .xlsm, .xlsb) and avoid use of ADO command object if no parameters are required:

User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement