将行从Excel插入SQL Server

时间:2014-06-27 22:02:19

标签: sql excel sql-server-2008 excel-vba vba

我正在处理从Excel 2010到SQL Server 2008的插入。我已经能够使用按钮成功地从Excel中将单个单元格值插入到SQL表中。现在我想插入很多行。我试图使用单个循环来迭代和插入值。我的代码如下:

Option Explicit
Private Conn As ADODB.Connection

Private Sub CommandButton1_Click()

Dim val1 As Integer
Dim i As Integer

Dim Conn As ADODB.Connection
Dim sConnString As String

For i = 1 To 2
 Cells(i, 1) = "val1"
Next i

'This will create the string to connect.
sConnString = "Driver={SQL Server};Data Source=**;Initial Catalog = **;Trusted_Connection =yes;"

'Create Connection and the Recordset Objects.
Set Conn = New ADODB.Connection

'Open the Connection in Order to Execute.
Conn.Open sConnString

Conn.Execute ("insert into TestTable(TestColumn) Values(" & val1 & ")")

'Clean
If CBool(Conn.State And adStateOpen) Then Conn.Close
    Set Conn = Nothing

End Sub

我在表中插入一个值,但它不是单元格A1:A2中的值。有人能告诉我我的循环和插入语句是如何错误的吗?有没有更好的方法来处理这个问题。我知道我目前只使用2行但是我将插入1100行,因此需要循环或迭代过程我假设。

感谢您的时间。

2 个答案:

答案 0 :(得分:2)

您正在错误地设置val1。变化:

Cells(i, 1) = "val1"

val1 = Cells(i, 1)

答案 1 :(得分:1)

尝试以下方法:

    Option Explicit
    Private Conn As AD

ODB.Connection

    Private Sub CommandButton1_Click()

    Dim val(1100) As Integer

    Dim i As Integer


    Dim Conn As ADODB.Connection
    Dim sConnString As String


    For i = 1 To 2
     val(i) = Cells(i,1).value





    'This will create the string to connect.

    sConnString = "Driver={SQL Server};Data Source=**;Initial Catalog = **;Trusted_Connection =yes;"



    'Create Connection and the Recordset Objects.

    Set Conn = New ADODB.Connection




    'Open the Connection in Order to Execute.

    Conn.Open sConnString

    Conn.Execute ("insert into TestTable(TestColumn) Values(" & val(i) & ")")





        'Clean
        If CBool(Conn.State And adStateOpen) Then Conn.Close
        Set Conn = Nothing

    Next i

    End Sub