繁体   English   中英

通过 VBA 将 Excel 范围推送到 SQL 表

[英]Push Excel Range to SQL Table via VBA

每次关联执行 VBA 宏时,我都需要将 Excel 中的范围推送到 SQL 表中的新行。 到目前为止,我已经在 Excel 中将数据分为单行多列(总共 110 个数据单元格)。 我现在的问题源于如何将 Excel 表中的每个单独的单元格插入 SQL 表中的相应列和第一个行。 我已经对互联网进行了一些相当广泛的搜索,但没有发现任何与我想要做的事情相近的东西。

是否有正确的程序允许我将 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。

我能够使用以下命令成功地将整行从 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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM