如何使用Excel宏连接到SQL Server?

时间:2016-09-21 08:21:26

标签: sql-server excel vba excel-vba

我有SQLEXPRESS个连接详情。我想使用VBA方式连接到数据库,并将数据从SQL Server表items导出到当前Excel工作簿和指定工作表中的新工作表。

我尝试从excel“外部数据”导入数据,在将其添加到excel工作簿时为我提供了全表。

如何从外部表格中仅添加1或2列Excel?

更新:我的代码现在是

Sub SQL_Connection()

Dim con As ADODB.Connection
Dim rs As ADODB.Recordset
Dim query As String
Set con = New ADODB.Connection
Set rs = New ADODB.Recordset

strCon = "Provider=SQLOLEDB; " & _
    "Data Source="\\localhost\SQLEXPRESS"; " & _
    "Initial Catalog=catalog;" & _
    "User ID=User; Password=password; Trusted_Connection=yes"
con.Open (strCon)
End Sub

获取编译错误:

  

语法错误

1 个答案:

答案 0 :(得分:0)

您首先需要创建并打开与数据库的连接。在这里,我发布了三行的示例示例:

Sub Button1_Click()

Dim conn As New ADODB.Connection
Dim iRowNo As Integer
Dim sCustomerId, sFirstName, sLastName As String

With Sheets("Customers")

    'Open a connection to SQL Server
    conn.Open "Provider=SQLOLEDB;Data Source=TESTpc\SQLEXPRESS;Initial Catalog=ExcelSQLServerDemo;Trusted_connection=yes"

   'Skip the header row
    iRowNo = 2

    'Loop until empty cell in CustomerId
    Do Until .Cells(iRowNo, 1) = ""
        sCustomerId = .Cells(iRowNo, 1)
        sFirstName = .Cells(iRowNo, 2)
        sLastName = .Cells(iRowNo, 3)

        'Generate and execute sql statement to import the excel rows to SQL Server table
        conn.Execute "INSERT into dbo.Customers (CustomerId, FirstName, LastName) values ('" & sCustomerId & "', '" & sFirstName & "', '" & sLastName & "')"

        iRowNo = iRowNo + 1
    Loop

    MsgBox "Customers Exported To Database"

    conn.Close
    Set conn = Nothing

    End With
End Sub

即使有更有效的方法来导出数据。此示例仅供参考。