|
楼主 |
发表于 2020-12-7 22:38
|
显示全部楼层
再发一个《ExcelVBA与数据库整合应用范例精讲》中的实例代码:
实例5-8 将工作表数据保存到已有的Access数据库(数组方式)(ADO)AddNew
- Public Sub 实例5_8()
- Dim myData As String, myTable As String
- Dim wb As Workbook
- Dim ws As Worksheet
- Dim myDataArrary As Variant
- Dim cnn As ADODB.Connection
- Dim rs As ADODB.Recordset
- Set wb = ThisWorkbook
- Set ws = wb.Sheets("总公司")
- myData = wb.Path & "\myData.mdb"
- myTable = "总公司销售记录"
- With ws.Cells(1, 1).CurrentRegion
- myDataArray = .Value
- End With
- Set cnn = New ADODB.Connection
- With cnn
- .Provider = "microsoft.jet.oledb.4.0"
- .Open myData
- End With
- n = ws.Range("A65536").End(xlUp).Row
- For i = 2 To n
- Sql = "select * from " & myTable _
- & " where 日期=#" & Format(ws.Cells(i, 1).Value, "yyyy-mm-dd") & "#" _
- & " and 商品名称='" & Cells(i, 2).Value & "'" _
- & " and 规格='" & Cells(i, 3).Value & "'" _
- & " and 单价=" & Cells(i, 4).Value _
- & " and 销售量=" & Cells(i, 5).Value
- Set rs = New ADODB.Recordset
- rs.Open Sql, cnn, adOpenKeyset, adLockOptimistic
- If rs.RecordCount = 0 Then
- rs.AddNew
- For j = 1 To rs.Fields.Count
- rs.Fields(j - 1) = myDataArray(i, j)
- Next j
- rs.Update
- Else
- For j = 1 To rs.Fields.Count
- rs.Fields(j - 1) = myDataArray(i, j)
- Next j
- rs.Update
- End If
- Next i
- MsgBox "数据保存完毕!", vbInformation + vbOKOnly
- rs.Close
- cnn.Close
- Set wb = Nothing
- Set ws = Nothing
- Set rs = Nothing
- Set cnn = Nothing
- End Sub
复制代码
|
|