【问题标题】:Insert Rows From Excel into SQL Server将行从 Excel 插入 SQL Server
【发布时间】:2014-08-19 03:05:07
【问题描述】:

我正在处理从 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 行,因此我假设需要一个循环或迭代过程。

感谢您的宝贵时间。

【问题讨论】:

  • 你得到什么值而不是A1:A2

标签: sql sql-server-2008 excel vba


【解决方案1】:

您错误地设置了 val1。变化:

Cells(i, 1) = "val1"

val1 = Cells(i, 1)

【讨论】:

    【解决方案2】:

    试试下面的:

        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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-01-28
      • 2020-11-09
      • 2020-11-09
      • 2016-03-16
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多