0

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.

4
  • What does Debug.Print Range("Cell1") & Range ("Cell2") return in the Immediate Window? Commented Feb 13, 2023 at 19:21
  • What does "not working" mean - error message, wrong result, nothing happens? What is content of those cells? The concatenated result should be a valid SQL statement. This SQL statement is more than 32,767 characters long? When concatenated, should you also concatenate a space between the parts? Commented Feb 13, 2023 at 19:32
  • @BigBen Huh I do see the cell values, but they are jumbled in that Cell1's range starts midway (not at the beginning), joins correctly into Cell2 then the beginning that was missing from Cell1 is suddenly appended at the end...... weird. Commented Feb 13, 2023 at 19:41
  • 1
    The immediate window has a 200 line limit so it should show the last 200 lines of the commandtext. Commented Feb 13, 2023 at 21:10

1 Answer 1

1

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
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.