代码之家  ›  专栏  ›  技术社区  ›  Anu

如何使用Excel VBA从Excel更新MSSQL

  •  0
  • Anu  · 技术社区  · 6 年前

    当前情况

    我在MSSQL中有一个数据库,目前它可以通过以下方式链接到Excel。

    连接到MSSQL的Excel表如下

    MSSQL表如下

    目前如果我更新我的mssql表,excel表会相应地更新

    我需要什么

    我要反向手术。意味着每当我更新excel表时,mssql也需要更新。这有可能吗?

    连接到MSSQL的Excel表如下

    enter image description here

    MSSQL表如下

    enter image description here

    目前如果我更新我的mssql表,excel表会相应地更新

    我需要什么

    我要反向手术。意味着每当我更新excel表时,mssql也需要更新。这有可能吗?

    1 回复  |  直到 6 年前
        1
  •  0
  •   Anu    6 年前

    我可以通过使用以下代码来正确地执行此操作

    Sub updateSqlFromExcel()
    Dim cnn As ADODB.connection
    Dim uSQL As String
    Set cnn = New connection
        cnnstr = "Provider=SQLOLEDB; " & _
                "Data Source=myServer; " & _
                "Initial Catalog=myDatabaseName;" & _
                "User ID=username;" & _
                "Password=password;" & _
                "Trusted_Connection=No"
                Set rngName = ActiveCell
        cnn.Open cnnstr
        
        excelId = ActiveCell.Value 'This is just an example
        excelSeq = ActiveCell.Offset(0, 1).Value 'This is just an example
        excelName = ActiveCell.Offset(0, 2).Value 'This is just an example
        
        uSQL = "UPDATE myTableName SET Name = '" & excelName & "', Seq = '" & excelSeq & "' WHERE ID= '" & excelId & "' "
        cnn.Execute uSQL
        ActiveWorkbook.RefreshAll
        MsgBox "Updated successfully. But please wait until background refresh finish before close excel", vbInformation, "Success"
        cnn.Close
        Set cnn = Nothing
    End Sub

    myServer myDatabaseName ,请 username password myTableName 根据您的设置,以便此宏工作。另外,请添加参考库 Microsoft ActiveX Data Objects 2.8 Library 并勾选复选框。按“确定”即可开始。