【问题标题】:Push Excel Range to SQL Table via VBA通过 VBA 将 Excel 范围推送到 SQL 表
【发布时间】:2020-03-09 17:38:50
【问题描述】:

每次员工执行 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 插入语句来添加记录,或打开一个可编辑的记录集,在该记录集上调用 AddNew,添加您的字段值,然后调用 Update,例如参见 vb-helper.com/howto_ado_insert.htmldocs.microsoft.com/en-us/sql/ado/reference/ado-api/…。跨度>
  • 这两种方法的示例:stackoverflow.com/questions/10708077/…
  • 我假设您已经考虑过从 power query 查询 excel,否定了涉及 sql 的要求...?
  • @LJ01 我已经考虑过了,但是 ISO/IATF 要求记录保留 10 年,所以我希望有一个地方可以永久保存它,而不是让成千上万的 Excel 表格四处飘荡。

标签: sql excel database vba ssms


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 2017-11-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-04-10
    • 2018-03-29
    • 1970-01-01
    相关资源
    最近更新 更多