简体   繁体   English

VBA宏将SQL错误代码复制到Excel中

[英]VBA macro to Copy a SQL error code into Excel

I am trying to write/adopt a macro in VBA to copy a SQL query into Excel. 我正在尝试在VBA中编写/采用宏以将SQL查询复制到Excel中。 I have it connecting and executing. 我有它连接并执行。 When I run it manually in SQL, this is the error code in SQL: 当我在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'.

Looks like its not a great query, but what interests me is the number of rows affected. 看起来它不是一个很好的查询,但是让我感兴趣的是受影响的行数。

Here is the latter portion of the VBA code that someone more skilled than me had used for a different query that works to paste the table result in A1: 这是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

This code works for a properly-executed SQL query. 此代码适用于正确执行的SQL查询。 Is there a way to copy the error message? 有没有办法复制错误消息?

Ideally what I want in cell A1 in Excel is just "8661". 理想情况下,我在Excel的单元格A1中想要的只是“ 8661”。

Thanks! 谢谢!

edit: Currently the error message in VBA upon executing the "cmd1.Execute" line is: 编辑:当前在执行“ cmd1.Execute”行时在VBA中的错误消息是:

Run-time error '-2147217900 (80040e14)': Automation error

Maybe you can try with this code... It shows the error on a message box. 也许您可以尝试使用此代码...它在消息框中显示错误。

Option Explicit

Public Sub Connect()

On Error GoTo InvalidValue:

Dim myCn As MyServer
Set myCn = New MyServer

Dim rs As ADODB.Recordset
Set rs = New ADODB.Recordset

rs.Open "Select * from myTable", myCn.GetConnection

Range("A1").CopyFromRecordset rs

rs.Close
myCn.Shutdown

Set rs = Nothing
Set myCn = Nothing

Exit Sub

InvalidValue:

MsgBox Err.Number & " " & Err.Description

End Sub

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM