|
困扰我好长时间了,请各位高手帮下忙,说下要求:
1、excel表格与Access表一样,不需新增字段,只需要把excel表格中sheet1中数据导入Access表。
2、请使用ADO
3、如果excel表格中数据ID与Access表数据ID相同,则更新Access,如果没有,则新增。
我这里有一个excel导入Access的代码,速度很快,但我不会转换,用于Access读取excel数据,现贴出来,供大家参考下:
Public Sub 导入数据到ACCESS()
Dim mydata As String, mytable As String, SQL As String
Dim cnn As ADODB.Connection
Dim rs As ADODB.Recordset
Dim rsx As ADODB.Recordset
Dim i As Long, n As Long
mydata = ThisWorkbook.Path & "\成绩.mdb" '指定数据库
mytable = "成绩" '指定数据表
n = Sheets("Sheet1").Range("A65536").End(xlUp).Row '指定要保存数据的记录数(行数)
'建立与数据库的连接
Set cnn = New ADODB.Connection
With cnn
.Provider = "microsoft.jet.oledb.4.0"
.Open mydata
End With
'建立查询
mysql = "select* from " & mytable
Set rs = New ADODB.Recordset
rs.Open mysql, cnn, adOpenKeyset, adLockOptimistic
For i = 2 To n
'查询是否已经存在了某条记录
SQL = "select * from " & mytable & " where 学号='" & Cells(i, 1).Value & "'"
Set rsx = New ADODB.Recordset
rsx.Open SQL, cnn, adOpenKeyset, adLockOptimistic
If rsx.RecordCount = 0 Then
rsx.AddNew
For j = 1 To rsx.Fields.Count
rsx.Fields(Cells(1, j).Value) = Cells(i, j).Value
Next j
rsx.Update
Else
For j = 2 To rsx.Fields.Count
rsx.Fields(j - 1) = Cells(i, j).Value
Next j
rsx.Update
End If
Next i
MsgBox "数据保存完毕!", vbInformation + vbOKOnly
rs.Close
cnn.Close
Set rs = Nothing
Set rsx = Nothing
Set cnn = Nothing
End Sub |
本帖子中包含更多资源
您需要 登录 才可以下载或查看,没有帐号?注册
x
|