【问题标题】:Run SQL Select query from .sql file using VBA in Excel在 Excel 中使用 VBA 从 .sql 文件中运行 SQL Select 查询
【发布时间】:2012-05-19 05:24:16
【问题描述】:

为了创建动态选择语句,我目前正在创建一个临时文件来保存查询(由于使用了连接和解码的数量,30k + 字符)。我想使用这个具有完整选择语句的临时文件将数据返回到 excel 中。

使用我当前的代码,我只能运行一个简短的选择语句。由于某种原因,我创建的字符串似乎被截断了。

这是我正在使用的用于创建文件并当前尝试运行相同字符串的代码的 sn-p。

' Set file details
fileDir = "C:\temp\"
filePath = "C:\temp\" & node & "_SRO_TCs.sql"

'check if directory exists, if not create it
If Dir(fileDir, cbDirectory) = "" Then
MkDir fileDir
End If

' open the file
Open filePath For Output As #1

'Write to file
outputText = sqlQuery3
Print #1, outputText

'open connection
sqlCon.ConnectionString = Conn
  'Cn.CursorLocation = adUseClient
sqlCon.Open

'set and execute sql command
Set sqlCommand.ActiveConnection = sqlCon
sqlCommand.CommandText = sqlQuery3
sqlCommand.CommandType = adCmdText
sqlCommand.Execute

'open recordset
Set sqlRecordSet.ActiveConnection = sqlCon
sqlRecordSet.Open sqlCommand


'copy data to excel
ActiveSheet.Range("A1").CopyFromRecordset (sqlRecordSet)  <<<< This is where i get an error returned when stepping through the code - "Run-time error '91': Object variable or With block variable not set"

'close connections
sqlRecordSet.Close
sqlCon.Close

'Close file
Close #1

当我检查创建的文件时,它有一个有效的 sql select 语句。我希望能够运行这个文件或字符串。请帮忙!

【问题讨论】:

  • 您正在打开文件进行输出并将 sqlQuery3 写入文件。您的意思是将文件读入一个名为 sqlQuery3 的字符串变量中吗?
  • @Remou sqlQuery3 是正在写入文件的查询,它已经包含选择字符串。我想要一种使用创建的文件而不是 sqlQuery3 的方法,因为当我尝试通过 sqlCommand 传递 sqlQuery3 时,它会被截断。
  • @Tony - 我认为您对截断有误。为什么你认为你的 SQL 被截断了?我遇到的唯一限制是单个 Oracle SQL 查询的最大大小大于 256 个字符。
  • @TimWilliams 我使用的 sql 查询有 30,500 多个字符长。如果我使用相同的 vba 代码并将查询截断为更短(这并不能满足我的需要,仅用于测试),则代码可以正常工作。当查询很长时,我会遇到大量错误。无论哪种方式,问题是,如何在不加载到字符串变量的情况下从 .sql 文件运行 sql 查询?
  • 要使用 ADO 运行查询,您必须将 SQL 加载到字符串中,因此您又回到了原点。在将 sqlRecordset 复制到工作表之前,您是否检查过以确保它不是 EOF?

标签: sql oracle vba excel excel-2007


【解决方案1】:

Command Execute 方法如下所示

Set recordset = command.Execute( RecordsAffected, Parameters, Options )

您的代码完全不同。之前没有仔细看你的代码,因为你说它可以使用更短的 SQL 语句。

【讨论】:

    猜你喜欢
    • 2015-02-07
    • 1970-01-01
    • 2023-03-17
    • 1970-01-01
    • 1970-01-01
    • 2016-12-28
    • 1970-01-01
    • 1970-01-01
    • 2023-01-25
    相关资源
    最近更新 更多