Karen Zhang
Karen Zhang

Reputation: 19

Inject two ranges into SQL Command Text, Excel VBA

Having some trouble with my macro where I need to inject two ranges into a SQL query. The reason being that it exceeds Excel's character limit for 1 cell, so I have used a formula to split the query between 2 (keeping in mind spaces for the split to keep the syntax correct).

However, my VB to inject both the ranges together is not working so it's clear there's something I'm not considering correctly. The error is Run-time error 1004: Application-defined or object-defined error

Here's how it currently appears:

With ActiveWorkbook.Connections("Qry").ODBCConnection
.CommandText = Range("Cell1") & Range ("Cell2")
End With

I have also tried to add .Value, as well as declaring the ranges before and then calling them. Note: Cell1 is the name I have given the cell.

When using Debug.Print on Range("Cell1") & Range ("Cell2"), the statement is jumbled, Cell1 starts midway before joining correctly into Cell2, then the beginning part of Cell1 abruptly starts again.

Upvotes: 0

Views: 99

Answers (1)

CDP1802
CDP1802

Reputation: 16267

Immediate window is limited to 200 lines so debug.print won't show the full text. Write the sql to a file and maybe test it in database client.

Dim sql as string, ts
sql = Range("Cell1") & Range("Cell2")
With CreateObject("Scripting.FileSystemObject")
    Set ts = .createTextFile("debug.sql")
    ts.Write sql
    ts.Close
End With

Upvotes: 1

Related Questions