将两个范围插入到SQL命令文本中,Excel VBA

huangapple go评论97阅读模式
英文:

Inject two ranges into SQL Command Text, Excel VBA

问题

有些问题是关于我的宏,我需要将两个范围插入到SQL查询中。原因是它超出了Excel一个单元格的字符限制,所以我使用了一个公式将查询分成两部分(考虑到分割时保持语法正确的空格)。

然而,我的VB用于将两个范围注入在一起的代码不起作用,所以很明显我没有正确考虑到某些事情。错误是运行时错误1004:应用程序定义或对象定义的错误。

这是当前的代码:

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

我也尝试添加.Value,以及在调用它们之前声明范围。注意:Cell1是我给这个单元格起的名字。

当在Debug.Print上使用Range("Cell1") & Range("Cell2")时,语句混乱了,Cell1在正确连接到Cell2之前中途开始,然后Cell1的开始部分突然重新开始。

英文:

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.

答案1

得分: 1

即时窗口仅限于200行,所以debug.print不会显示完整的文本。将SQL写入文件,然后在数据库客户端中进行测试。

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

<details>
<summary>英文:</summary>

Immediate window is limited to 200 lines so debug.print won&#39;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

huangapple
  • 本文由 发表于 2023年2月14日 03:20:15
  • 转载请务必保留本文链接:https://go.coder-hub.com/75440352.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定