将行从Excel插入到SQL Server中

我正在从Excel 2010插入到SQL Server 2008中。我已经能够使用button成功地将单个单元格值从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行,因此我假设需要循环或迭代过程。

感谢您的时间。

您正在设置val1不正确。 更改:

 Cells(i, 1) = "val1" 

 val1 = Cells(i, 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