我的要求是允许从Excel直接编辑SQL Server表。只是更新,而不是删除或插入。
我当前的解决方案是使用内置的OLE DB连接工具将数据加载到Excel工作表中。然后使用下面的代码捕获表上的工作表更改,并通过ADODB连接执行SQL命令。
[从本质上讲,它是2011年this的配对版本。]
这是最佳做法吗?还是有更好的方法来达到相同的结果?
Public oldValue As Variant
Private Sub Worksheet_SelectionChange(ByVal Target As Range)
If Target.Cells.CountLarge > 1 Or IsEmpty(Target) Then Exit Sub
oldValue = Target.Value
End Sub
Private Sub Worksheet_Change(ByVal Target As Range)
Dim KeyCells As Range
Dim i As Integer
Dim SQLTable As String
Dim ID_Name As String
Dim ID_Value As String
Dim Field_Name As String
Dim Field_Value As String
Dim store As Variant
Dim reset As Integer
Set KeyCells = ListObjects("Table1").Range
If Intersect(Target, KeyCells) Is Nothing Or Target.Cells.Count > 1 Then Exit Sub
SQLTable = "[dbo].[My_Table]"
ID_Name = ListObjects("Table1").HeaderRowRange(1).Value
ID_Value = Cells(Target.Row, 1).Value
Field_Name = ListObjects("Table1").HeaderRowRange(Target.Column).Value
Field_Value = Target.Value
Call SqlUpdate(SQLTable, ID_Name, ID_Value, Field_Name, Field_Value, 0, reset)
End Sub
Sub SqlUpdate(SQLTable As String, ID_Name As String, ID_Value As String, Field_Name As String, Field_Value As String, Confirm As Integer, ByRef reset As Integer)
Dim conn As ADODB.Connection
Set rs = New ADODB.Recordset
Dim sConnString As String
Dim SQLCommand As String
Dim iCols As Integer
Dim i As Integer
Dim server As String
Dim DataBase As String
server = "My_server"
DataBase = "My_databaase"
' Create the connection string.
sConnString = "Provider=SQLOLEDB;Data Source=" & server & ";" & _
"Initial Catalog=" & DataBase & ";" & _
"Integrated Security=SSPI;"
' Create and Open the Connection.
Set conn = New ADODB.Connection
conn.Open sConnString
' Execute
SQLCommand = "update " & SQLTable & " set " & Field_Name & " = '" & Field_Value & "' where " & ID_Name & " = '" & ID_Value & "';"
On Error GoTo ErrHandler:
Set rs = conn.Execute(SQLCommand, RecordsAffected:=i)
' Clean up
If CBool(conn.State And adStateOpen) Then conn.Close
Set conn = Nothing
Set rs = Nothing
reset = 0
Exit Sub
ErrHandler:
reset = 1
MsgBox "Invalid Value: Table not updated."
End Sub