将SQL信息拉入Excel

时间:2016-06-20 15:10:35

标签: sql-server excel excel-vba sql-server-2012 connection-string vba

我以前能够创建连接并将整个表格甚至一两列从SQL引入Excel。

现在我希望用户将ID输入到Userform中,然后使用VBA运行SQL代码来获取相应的ID,FirstName,LastName。然后它应该将该信息粘贴到"条目"的第一个空白行A,B,C上。片材。

我在这行代码中收到错误说明:运行时错误' 1004'应用程序定义或对象定义的错误。

With ActiveSheet.ListObjects.Add(SourceType:=0, Source:=Array("OLEDB;Provider=SQLOLEDB.1;Integrated Security=SSPI;Persist Security Info=True;Data Source=xxx.xxx.xxx.xxx;Use Procedure for Prepare=1;Auto Translate=True;Packet Size=4096;Use Encryption for Data=False;Tag with column collation when possible=False;Initial Catalog=DBName"), Destination:=Sheets("Entry").Range("A1").End(xlDown).Offset(1, 0)).QueryTable

大部分内容我都不明白,只是有些人把我的代码交给了我试图重新使用的代码。仍然有效的旧代码是这样的:

With ActiveSheet.ListObjects.Add(SourceType:=0, Source:=Array( _
        "OLEDB;Provider=SQLOLEDB.1;Integrated Security=SSPI;Persist Security Info=True;Data Source=xxx.xxx.xxx.xxx;Use Procedure for Prepare=1;Auto " _
        , _
        "Translate=True;Packet Size=4096;Use Encryption for Data=False;Tag with column collation when possibl" _
        , "e=False;Initial Catalog=DBName"), Destination:=Range("Database!$A$1")). _
        QueryTable

这些之间的区别在于,我不希望将代码放在一个设置单元格中,代码超过几十万行数据,而是希望代码位于第一个空白行中,而只是拉过那一条记录。但每次运行时都需要进入下一行。

使用旧代码,它创建了一个实际的表,我猜测它与最终表明QueryTable的事实有关。我宁愿只有数据而不是表格式。如果有办法改变它,那就太好了。

此外,在上一版本中,查询仅从一个表中提取,.SourceConnectionFile = _链接指向该文件。新代码需要链接到两个表,所以有两个文件,因为我无法让它创建一个连接文件,并选择了两个表。如果你可以提供帮助,那就太好了。

我正在使用Excel 2013 Standard和SQL Server 2012.如果您需要更多信息,请与我们联系。

所以这就是我到目前为止尝试@Kyle建议的ADO方法。 OCR是以前代码中Userform的变量输入。当它运行时,它不会出错,但它不会粘贴任何数据。

Sub Code()

    Sheets("Entry").Select

    On Error Resume Next

Const adOpenStatic = 3
Const adLockOptimistic = 3
Const adCmdText = &H1

Set objConnection = CreateObject("ADODB.Connection")
Set Objrecordset = CreateObject("ADODB.Recordset")

ConnectionString = "Provider=SQLOLEDB;Data Source=xxx.xxx.xxx.xxx;Initial Catalog=DBName;User ID=MyUN;Password=MyPW"
objConnection.Open


Objrecordset.Open "Select B.ID, B.Firstname, B.Lastname From TableA as A Join TableB as B on A.ID = B.ID Where A.Cardnumber =" & OCR, objConnection, adOpenStatic, adLockOptimistic, adCmdText

If Not Objrecordset.EOF Then
    Sheets("Entry").Range("A1").End(xlDown).Offset(1, 0).CopyFromRecordset Objrecordset
    Objrecordset.Close
Else
MsgBox "Did not Work"
End If

End Sub

1 个答案:

答案 0 :(得分:0)

所以我能够使用它:

Sub Code()

    Sheets("Entry").Select

    Dim Cn As ADODB.Connection
    Dim Server_Name As String
    Dim Database_Name As String
    Dim User_ID As String
    Dim Password As String
    Dim SQLStr As String
    Dim rs As ADODB.Recordset
    Set rs = New ADODB.Recordset

    Server_Name = "" ' Enter your server name here
    Database_Name = "" ' Enter your database name here
    User_ID = "" ' enter your user ID here
    Password = "" ' Enter your password here
    SQLStr = "SELECT B.ID, B.FirstName, B.LastName From Table A Join Table B as B on A.ID = B.ID Where A.CardNumber ='" & OCR & "'" ' Enter your SQL here

    Set Cn = New ADODB.Connection
    Cn.Open "Driver={SQL Server};Server=" & Server_Name & ";Database=" & Database_Name & _
    ";Uid=" & User_ID & ";Pwd=" & Password & ";"

    rs.Open SQLStr, Cn, adOpenStatic
     ' Dump to spreadsheet
    With Worksheets("Entry").Range("A1").End(xlDown).Offset(1, 0) ' Enter your sheet name and range here
        .ClearContents
        .CopyFromRecordset rs
    End With
     '            Tidy up
    rs.Close
    Set rs = Nothing
    Cn.Close
    Set Cn = Nothing



End Sub