VBA ADO参考用户定义的错误

时间:2016-07-14 17:09:59

标签: python excel vba excel-vba adodb

关于我正在努力实现的目标的小背景我正在编写一个在我的Python代码中执行以查询SQL的vba脚本。我一直被困在研究这个ADO.Recordset,它不断给我一个'用户定义的错误'我已经将所有必需的引用(据我所知)添加到GUID调用的代码中。

请参阅以下代码。

import pyodbc
import os
import win32com.client as win32
import comtypes, comtypes.client

xl = win32.gencache.EnsureDispatch('Excel.Application')
xl.Visible = True
ss = xl.Workbooks.Add()
sh = ss.ActiveSheet

xlmodule = ss.VBProject.VBComponents.Add(1)

sCode = '''Sub Download_Standard_BOM()
'Initializes variables
Set cn = CurrentProject.Connection
Set rst = New ADODB.Recordset
Dim cn As Object: Set cn = CreateObject("ADODB.Connection")
Dim rst As New ADODB.Recordset
Dim ConnectionString As String
Dim StrQuery As String


    ConnectionString = "Provider=SQLOLEDB; Network Library=dbmssocn;Password=******;User ID=******;Initial Catalog=*****;Data Source=************;"

    cnn.Open ConnectionString

    ThisWorkbook.VBProject.References.AddFromGuid "{2A75196C-D9EB-4129-B803-931327F72D5C}", 2, 3

    ThisWorkbook.VBProject.References.AddFromGuid "{000204EF-0000-0000-C000-000000000046}", 2, 3

    ThisWorkbook.VBProject.References.AddFromGuid "{00020813-0000-0000-C000-000000000046}", 2, 3

    ThisWorkbook.VBProject.References.AddFromGuid "{00020430-0000-0000-C000-000000000046}", 2, 3

    ThisWorkbook.VBProject.References.AddFromGuid "{00000600-0000-0010-8000-00AA006D2EA4}", 2, 3

    ThisWorkbook.VBProject.References.AddFromGuid "{00025E01-0000-0000-C000-000000000046}", 2, 3

    ThisWorkbook.VBProject.References.AddFromGuid "{00000300-0000-0010-8000-00AA006D2EA4}", 2, 3

    cnn.CommandTimeout = 900

    StrQuery = "SELECT * FROM car_search WHERE search_id = 9999999"

    rst.Open StrQuery, cnn

    Sheets(1).Range("A2").CopyFromRecordset rst
End Sub'''

xlmodule.CodeModule.AddFromString(sCode)
xl.Run ('Download_Standard_BOM')

我感谢你们提供的所有帮助!

2 个答案:

答案 0 :(得分:1)

或者,您可以直接使用Python连接到SQL Server(无COM接口)并将数据输出为csv或Excel格式(后者使用pandas,Python的数据分析包):

以下是CSV和ODBC DRIVER方法:

import pyodbc
import csv

constr = 'DRIVER={SQL Server};SERVER=servername;DATABASE=database;' \
         'Trusted_Connection=yes;UID=username;PWD=password'
conn = pyodbc.connect(constr)

cur = conn.cursor()
cur.execute("SELECT * FROM car_search WHERE search_id = 9999999")

with open('Output.csv', 'w', newline='') as csvfile:
    writer = csv.writer(csvfile)
    writer.writerow([i[0] for i in cur.description])   # COLUMNS
    for row in cur.fetchall():        
        writer.writerow(row)                           # DATA ROWS

cur.close()
conn.close()

以下是大熊猫(使用read_sqlto_csvto_excel)和OLEDB PROVIDER方法:

import adodbapi
import pandas as pd

constr = 'PROVIDER=SQLOLEDB.1;Data Source=servername;Initial Catalog=database;' \
         'Integrated Security=SSPI;Trusted_Connection=yes;' \ 
         'User ID=username;Password=password'    
conn = adodbapi.connect(constr)

df = pd.read_sql("SELECT * FROM car_search WHERE search_id = 9999999", conn)
df.to_csv('Output.csv', index=False)
df.to_excel('Output.xlsx', index=False)

conn.close()

当然,ODBC / OLEDB也可以互换,对齐相应的模块(pyodbc / pypyodbc vs adodbapi)。

答案 1 :(得分:0)

如果使用后期绑定,则无需添加任何引用:

sCode = '''Sub Download_Standard_BOM()
'Initializes variables


Dim cnn As Object: Set cnn = CreateObject("ADODB.Connection")
Dim rst As Object: Set rst = CreateObject("ADODB.Recordset")

Dim ConnectionString As String
Dim StrQuery As String


    ConnectionString = "Provider=SQLOLEDB; Network Library=dbmssocn;Password=******;" & _
      "User ID=******;Initial Catalog=*****;Data Source=************;"

    cnn.Open ConnectionString
    cnn.CommandTimeout = 900

    StrQuery = "SELECT * FROM car_search WHERE search_id = 9999999"

    rst.Open StrQuery, cnn

    Sheets(1).Range("A2").CopyFromRecordset rst
End Sub'''