我怎么能写这个VBA代码? (如何更新/删除/添加Excel(2013)文件中的记录到SQL Server 2012数据库)
Title:如何从Excel更新/删除/添加记录(2013 )
文件到SQL Server 2012数据库?
我从数据库(employee_name表)连接了一个表(Excel表)。
I connected a table (Excel sheet) from the database (employee_name table).
现在我可以在Excel文件表1中看到一个表和记录列表。我将刷新时间设置为1分钟。
Now I can see a table and record list in my Excel file-sheet1. I set the refresh time as 1 minute.
我怎样才能更新/删除/添加Excel(2013)文件中的记录到SQL Server 2012数据库表?
How could I update/delete/add records from the Excel (2013) file to SQL Server 2012 database table?
我想使用Excel文件
作为前端,并使用SQL Server数据库表作为后端。
我可以从Excel工作表中看到SQL Server数据库上的任何可用内容,但我无法从Excel编辑任何内容。
I can see whatever available on SQL Server database from the Excel sheet, but I am not able to edit anything from Excel.
我希望能找到一种从Excel工作表编辑SQL Server数据库记录的方法。
I wish can find a way to edit the SQL Server DB records from the Excel sheet.
谢谢。
M。
您可以使用下面的代码
you could use the code below
它将从当前表中删除然后从特定范围的单元格上传 - 将循环直到在第4行下面的Col A中找到空白通常我使用表单按钮操作这些 - 而不是定时 - 就好像某人在
自动更新它可能会损坏之前,你需要使用一些东西:你还需要在VB工具引用位上使用activex
it will delete from a current table then upload from a specific range of cells- will loop until a blank is found in Col A below row 4- normally I operate these using a form button- rather than a timed- as if someone accidentialy changfes something just before an auto uppdate it could corrupt- you also need to use activex on the VB tool references bit
D
Public con As ADODB.Connection
Sub check()
Function GetCon() As ADODB.Connection
If con Is Nothing Then
Set con = New ADODB.Connection
con.Open "provider=SQLOLEDB;Data Source= name of your sql system;Initial Catalog= name of specific database;Integrated Security=SSPI;"
End If
Set GetCon = con
End Function
Sub update_Z_DM_Import_Tbl()
Dim con As Connection
Dim rst As Recordset
Set con = New Connection
Dim row As Integer
row = 4
Set rst = GetCon.Execute("delete from Z_DM_Import_Tbl")
Do
Set rst = GetCon.Execute("INSERT INTO Z_DM_Import_Tbl(text1,Text2,float) SELECT '" & _
Replace(Cells(row, 1).Value, "'", "''") & "', '" & _
Replace(Cells(row, 2).Value, "'", "''") & "', '" & _
Replace(Cells(row, 3).Value, "'", "''") & "'")
row = row + 1
Loop Until Len(Cells(row, 1)) = 0
Set rst = GetCon.Execute("delete from Z_DM_Import_Tbl") ' insert code between brackets for what you want to do- update, insert etc from this table to the final table
End Sub