Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 7900315
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 3, 20262026-06-03T08:56:23+00:00 2026-06-03T08:56:23+00:00

I am looking to execute SQL SELECT statement inside a single cell in Excel,

  • 0

I am looking to execute SQL SELECT statement inside a single cell in Excel, using other cells as inputs to the SELECT statement. After some searching, I found that the sql.request function would have done exactly what I’m looking for. However, that function was deprecated in after 2002, and I’m running Excel 2007 and 2010 here at work. Citation

I have tried to create a Macro / VBA script that does the same thing, but haven’t been able to get very far with it. I do all my programming in LabVIEW, Mathematica, and SQL; I have no idea what’s going on in VBA. This is what I’ve managed to come up with:

Sub Test2()

' Declare the QueryTable object. I'm not actually sure why this line is here...
Dim qt As QueryTable

' Set up the SQL Statement
sqlstring = "SELECT `Substrate ID` FROM temp_table WHERE `id`=" & Range("A1").Value

' Set up the connection string, reference an ODBC connection
connstring = "ODBC;DSN=OWT_x64;"

' Now implement the connection, run the query, and add
' the results to the spreadsheet
With ActiveSheet.QueryTables.Add(Connection:=connstring, Destination:=Range("A22"), Sql:=sqlstring)
    .Refresh BackgroundQuery:=False
End With

End Sub

There are three primary issues with the above code:

  1. This code returns the column ID (“Substrate ID”) in cell A22, and the result of the SQL query in cell A23. I only want the result, and I only want it in cell A22. All queries are forced to return only 1 row and 1 column.
  2. I don’t know how to make it so that the output cell, A22, is whatever cell is active when the script is run. Also, the input cell, A1, should be the cell directly to the left (column-1) of the active cell.
  3. I don’t know how to turn this into an Excel function

    =sql.request(connection_string,[output_ref],[driver_prompt],[query_text],[col_names_logical])

    which is my final goal. This way, I can give this code to others at my company and they can easily use it.

The connection is a ODBC connection to a MySQL 5.6 database. The query is pretty simple, and along the lines of:

SELECT column FROM table WHERE id=excel_cell_value

as you can see from the VBA code that I have.

Currently, I run a query in a different Excel worksheet that returns all rows of the “id” and “Substrate ID” columns and then run VLOOKUP to find the item of interest. This is starting to become an issue, as our database size is growing quite fast.

So, I ask:

  1. How can I get rid of the column ID in the result?
  2. How can I turn this into a custom excel function? I’ve looked at Office.com and it doesn’t seem too difficult, but I need a working script first.
  3. -OR- Has anyone already made a custom function that they’re willing to share?

Thanks!

EDIT: Managed to get something working thanks to Tim’s link.

Function SQLQuery(sqlString As String, connString As String, Optional TimeOut As Integer) As String

SQLQuery = Error 'Assume an error happened

Dim conn As ADODB.Connection
Dim record As ADODB.Recordset

Set conn = New ADODB.Connection
conn.ConnectionString = connString
conn.Open
Set record = New ADODB.Recordset

If TimeOut > 0 Then
    conn.CommandTimeout = TimeOut
End If

record.Open sqlString, conn

Dim cols As Long
Dim i As Long

cols = record.Fields.Count   'Count how many columns were returned
If Not record.EOF Then   'Put results into comma-delimited string
    record.MoveFirst
    s = ""
    If Not record.EOF Then
        For i = 0 To cols - 1
            s = s & IIf(i > 0, ",", "") & record(i)
        Next i
    End If
End If

SQLQuery = s

End Function

However, it’s quite slow. Any ideas on how to speed it up?

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-03T08:56:24+00:00Added an answer on June 3, 2026 at 8:56 am

    Here’s a quick test of caching the connection. On a test worksheet with 100 lookups it reduced calculation time from about 18 sec to about 0.5 sec

    Remember though it will keep a connection open until you close Excel (or the VB environment gets reset).

    If you want to test the difference in your environment, you can comment out the marked line (don’t forget to also press the “stop” button in the VBE to clear the static variables).

    Function SQLQuery(sqlString As String, connString As String, _
                                      Optional TimeOut As Integer) As String
    
        Static cs As String
        Static conn As ADODB.Connection
    
        SQLQuery = Error 'Assume an error happened
        Dim s
    
        If conn Is Nothing Or connString <> cs Then
            Set conn = New ADODB.Connection
            conn.ConnectionString = connString
            conn.Open
            If TimeOut > 0 Then conn.CommandTimeout = TimeOut
            cs = connString '###comment this out to disable caching effect
        End If
    
        Dim record As New ADODB.Recordset
    
        record.Open sqlString, conn
    
        Dim cols As Long
        Dim i As Long
    
        cols = record.Fields.Count   'Count how many columns were returned
        If Not record.EOF Then   'Put results into comma-delimited string
            record.MoveFirst
            s = ""
            If Not record.EOF Then
                For i = 0 To cols - 1
                    s = s & IIf(i > 0, ",", "") & record(i)
                Next i
            End If
        End If
    
        SQLQuery = s
    
    End Function
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I'm using a SqlCommand to execute a sql statement on a SqlServer2005 db. (
Without using dynamic SQL, and other than an If ELSE is there any way
I am looking into using log shipping in a SQL Server 2005 environment. The
I am using LINQ select statement wrapped in a TransactionScope (to change the locking)
I'm looking for an effective way to execute a method everyday at 3PM regardless
I am looking for a way to not have a plugin execute on install.
I'm using SQLAlchemy as the ORM within an application i've been building for some
I am looking for a Java library/framework/technique of storing SQL statements in an external
I've only just started looking at Dapper.net and have just been experimenting with some
I could write a SP inside Mysql and excute with a call statement. But

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.