尝试使用Excel中的VBA连接到数据库时出错

时间:2012-12-27 06:35:09

标签: sql excel vba

我正在尝试使用excel中的VBA连接到数据库,但不知道出了什么问题。有什么建议吗?

这是代码。我想获取查询结果,然后同时将其放入Excel工作表

Private Sub CommandButton1_Click()

Dim dd As String
Dim nn As String

OMCS_Connection.Show

If OMCS_Connection.CommandButton1 = False Then

dd = OMCS_Connection.TextBoxa.Value
nn = OMCS_Connection.TextBoxb.Value
End If

Dim order_number As String
order_number = TextBox1.Text
Dim sql_query As String

Set ad = CreateObject("ADODB.Connection")      'create and open ODBC connection
ad.ConnectionString = "ODBC;DRIVER=IBM DB2 ODBC DRIVER - DB2COPY1; DSN=ODRPTDB;UID = " & dd & " ; PWD = " & nn & ";"
'UID=me"
ad.Open

sql_query = "SELECT" & _
                "CMOT.MFGNO AS MANUFACTURING_NUMBER," & _
                "'BOX' AS ORDER_TYPE," & _
                "CMOT.IDCUS AS CUSTOMER_ID," & _
                "CMOT.WTCTN AS WT_CUSTOMER_ID," & _
                "CMOT.PLORN AS ORDER_NUMBER," & _
                "CMOT.IDMAC AS MACHINE_TYPE," & _
                "CMOT.IDSMN AS MODEL_NUMBER," & _
                "'    ' AS NEW_MACHINE_TYPE," & _
                "'    ' AS NEW_MODEL_NUMBER," & _
                "CMOT.BOXSH AS PSSD," & _
                "CMOT.ALDPF AS RSSD," & _
                "COGUS.ITPDC AS REGION" & _
                "FROM DB2COATG.COS1S0T0 CMOT" & _
                "INNER JOIN COGUS.WTCTN_CONVERSION COGUS" & _
                "ON(COGUS.WTCTN = CMOT.WTCTN AND COGUS.REGIO = CMOT.REGIO)" & _
                "WHERE CMOT.PLORN IN  (" & order_number & ");"


Set RS = ad.Execute(sql_query)        'execute query

1 个答案:

答案 0 :(得分:0)

在ad.open尝试插入以下行之前 ad.CommandTimeout=0 如果查询运行时间过长,这应该可以防止查询超时。 如果这不起作用,那将有助于了解抛出错误的代码行。你知道如何思考代码吗?