通过VBA将Excel范围推入SQL表

问题描述 投票:0回答:1

我需要在员工每次执行VBA宏时将Excel中的范围推到SQL表中的新行。到目前为止,我已经在Excel中将数据分为单行和多列(总共110个单元格的数据)。我现在的问题源于如何将这些单独的单元格从Excel工作表中的每个插入到SQL表中相应的列和第一empty行中。我已经对互联网做了一些相当广泛的搜索,但发现几乎没有什么东西比我想做的要远。

是否有正确的过程可以让我将110列的行转储到SQL表的第一空行中?

我写了表格,并设置了范围:

Set DataBaseData = ActiveSheet.Range("DO1:HT1")

此外,我不知道以哪种方式打开与服务器,数据库和表的连接。到目前为止,这是我所追求的目标:

Sub Connection()
    Dim Conn As ADODB.Connection
    Dim Command As ADODB.Command

    Set Conn = New ADODB.Connection
    Set Command = New ADODB.Command

    Dim i As Integer
    Dim columnnumber As Integer

    i = 0

    Conn.ConnectionString = "Provider=SQLOLEDB; Data Source=[Nope];Initial Catalog=[NopeNope];User ID=[NopeNopeNope];Password=[AbsolutelyNot]; Trusted_Connection=no;"

    Conn.Open
    Command.ActiveConnection = Conn
End Sub

任何帮助将不胜感激。

[如果您对我要做什么感到好奇:我正在将一系列数据从CMM推送到数据库,以便我可以将数据存储所需的时间,然后将其回调给PowerBI和Minitab。

sql excel database vba ssms
1个回答
0
投票

我能够使用以下方法成功地将整个行从Excel写入SQL数据库:

Sub Connection()

  Const Tbl As String = "NEIN"

        Dim InsertQuery As String, xlRow As Long, xlCol As Integer

        Dim DBconnection As Object

        Set DBconnection = CreateObject("ADODB.Connection")

        DBconnection.Open "Provider=SQLOLEDB.1;Password=NEIN" & _
            ";Persist Security Info=false;User ID=NEIN" & _
            ";Initial Catalog=NEIN;Data Source=NEIN"

        InsertQuery = ""
        xlRow = 1   'only one row being used *as of now*, and that is the top row in the excel sheet
        xlCol = 119 'First column of data
        While Cells(xlRow, xlCol) <> ""

            InsertQuery = InsertQuery & "INSERT INTO " & Tbl & " VALUES('"

            For xlCol = 119 To 229 'columns DO1 to HT1
                InsertQuery = InsertQuery & Replace(Cells(xlRow, xlCol), "'", "''") & "', '"  'Includes mitigation for apostrophes in the data
            Next xlCol
            InsertQuery = InsertQuery & Format(Now(), "M/D/YYYY") & "')" & vbCrLf 'The last column is a date stamp, either way, don't forget to close that parenthesis

        Wend

        DBconnection.Execute InsertQuery
        DBconnection.Close
        Set DBconnection = Nothing

End Sub
© www.soinside.com 2019 - 2024. All rights reserved.