【发布时间】:2016-12-14 22:01:04
【问题描述】:
我正在尝试在 VBA 中编写/采用宏来将 SQL 查询复制到 Excel 中。 我有它连接和执行。当我在 SQL 中手动运行它时,这是 SQL 中的错误代码:
Msg 3701, Level 11, State 5, Line 1
Cannot drop the table '#MSP_History3', because it does not exist or you do not have permission.
(8661 row(s) affected)
Msg 3701, Level 11, State 5, Line 1
Cannot drop the table '#MSP1', because it does not exist or you do not have permission.
(8661 row(s) affected)
Msg 3701, Level 11, State 5, Line 1
Cannot drop the table '#MSP_PBP', because it does not exist or you do not have permission.
(8661 row(s) affected)
Msg 3701, Level 11, State 5, Line 1
Cannot drop the table 'dbo.MSP_History', because it does not exist or you do not have permission.
Msg 262, Level 14, State 1, Line 1
CREATE TABLE permission denied in database 'master'.
看起来它不是一个很好的查询,但我感兴趣的是受影响的行数。
这是 VBA 代码的后半部分,比我更熟练的人曾使用该代码进行不同的查询,该查询可以将表格结果粘贴到 A1 中:
'Open the connection.
cn.Open strConn
'
'Set and Execute SQL Command
Set cmd1.ActiveConnection = cn
cmd1.CommandText = SQLquery
cmd1.CommandType = adCmdText
cmd1.Execute
'Open Recordset
Set rs1.ActiveConnection = cn
rs1.Open cmd1
'Paste Column Headers into Spreadsheet
For Col = 0 To rs1.Fields.Count - 1
Range("A1").Offset(0, Col).Value = rs1.Fields(Col).Name
Next
'Copy Data to Excel
ActiveSheet.Range("A2").CopyFromRecordset rs1
Cells.Select
Cells.EntireColumn.AutoFit
此代码适用于正确执行的 SQL 查询。有没有办法复制错误信息?
理想情况下,我在 Excel 的单元格 A1 中想要的只是“8661”。
谢谢!
编辑:当前执行“cmd1.Execute”行时VBA中的错误消息是:
Run-time error '-2147217900 (80040e14)': Automation error
【问题讨论】:
标签: sql-server vba excel macros