ExcelBanter

ExcelBanter (https://www.excelbanter.com/)
-   Excel Programming (https://www.excelbanter.com/excel-programming/)
-   -   Use variables in sql statement (https://www.excelbanter.com/excel-programming/324870-use-variables-sql-statement.html)

Markantesp

Use variables in sql statement
 
I've built an sql string to get records from a database and store to excel.

sSql = "SELECT * FROM myTableName"

I want to replace myTableName with a variable (TableVar) to reference the
tablename typed in Cell A1.
I assigned the variable TableVar by doing the following:
TableVar = ActiveWorkbook.Worksheets("sheet1").Range("B1").Va lue
When I replace myTableName with TableVar, I get an error message that there
is no such table as TableVar.
What is the correct way to replace a table name with a variable?

Malcolm Makin[_2_]

Use variables in sql statement
 
You already have the table name in a variable, so you just need to
concatenate that variable into your sSql variable (rather than typing the
literal text TableVar). Do so like this:

sSql = "SELECT * FROM " & TableVar

That should get you on your way, as long as TableVar contains a valid name.

"Markantesp" wrote:

I've built an sql string to get records from a database and store to excel.

sSql = "SELECT * FROM myTableName"

I want to replace myTableName with a variable (TableVar) to reference the
tablename typed in Cell A1.
I assigned the variable TableVar by doing the following:
TableVar = ActiveWorkbook.Worksheets("sheet1").Range("B1").Va lue
When I replace myTableName with TableVar, I get an error message that there
is no such table as TableVar.
What is the correct way to replace a table name with a variable?


Glenn Ray[_3_]

Use variables in sql statement
 
Is your code constructed like this?

Dim TableVar, sSql as String
TableVar = trim(ActiveWorkbook.Worksheets("sheet1").Range("B1 ").Value)
sSql = "SELECT * FROM " & TableVar

Note that space after FROM; I've missed a few of those myself.

-Glenn Ray

"Markantesp" wrote:

I've built an sql string to get records from a database and store to excel.

sSql = "SELECT * FROM myTableName"

I want to replace myTableName with a variable (TableVar) to reference the
tablename typed in Cell A1.
I assigned the variable TableVar by doing the following:
TableVar = ActiveWorkbook.Worksheets("sheet1").Range("B1").Va lue
When I replace myTableName with TableVar, I get an error message that there
is no such table as TableVar.
What is the correct way to replace a table name with a variable?



All times are GMT +1. The time now is 02:45 AM.

Powered by vBulletin® Copyright ©2000 - 2024, Jelsoft Enterprises Ltd.
ExcelBanter.com