给你一个直接在Excel内上传数据到SqlServer的代码:
可适当修改,
FormName为数据库内的表格,
DBString为数据库连接字段,
Sub UploadData()
If FormName = "" Then Exit Sub
Dim a As New ADODB.Connection
Dim b As New ADODB.Recordset
a.Open DBString
RowCount = Application.CountA(Rows("1:1"))
For i = 2 To application.counta(range("a:a"))
sql = ""
Set b = Nothing
For j = 1 To RowCount - 1
sql = sql & "'" & Cells(i, j) & "', "
Next
sql = "insert into " & FormName & " values(" & sql & "'" & Cells(i, RowCount) & "')"
b.Open Source:=sql, ActiveConnection:=a
Next
MsgBox "OK!"
End Sub
方法是多样的,找到一个适合的即可,
要想完成你的任务,你需要了解数据库的连接属性,如下为连接字段,可根据你的实际情况来修改,基本参数的设置要靠自己,
Provider=SQLOLEDB.1;Persist Security Info=False;User id=md-inspection;PWD=mdOL20!31)25;Initial Catalog=Online_Inspection;Data Source=Cduvmdb01,1433
另外需要在VBE页面添加相关引用: