|
[广告] VBA代码宝 - VBA编程加强工具 · VBA代码随查随用 · 内置多项VBA编程加强工具 ★ 免费下载 ★ ★ 使用手册★
- Sub Button1_Click()
- Dim cnn As New ADODB.Connection
- Dim rs As ADODB.Recordset
- Dim Cat As New ADOX.Catalog
- Dim myPath As String
- Dim myData As String
- Dim p As String
- Dim SQL As String
- Dim d As Object, arr, brr(), i&, j&, m&
- myPath = ThisWorkbook.Path & ""
- p = Dir(myPath & "A list *.xls?")
- If p = "" Then
- MsgBox "没有发现数据源工作簿,无需更新。", vbInformation, "提醒"
- Exit Sub
- End If
- myData = myPath & "data.accdb"
- myTable = Split(p, " ")(0) & Split(p, " ")(1)
- If Dir(myData) = "" Then Cat.Create "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & myData
- cnn.Open "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & myData
- Set rs = cnn.OpenSchema(adSchemaTables, Array(Empty, Empty, myTable, Empty))
- If rs.EOF Then
- SQL = "CREATE TABLE " & myTable & "([Number] text(50),[Assetment Number] LONGTEXT)"
- Else
- SQL = "DELETE FROM " & myTable
- End If
- cnn.Execute SQL
- Set d = CreateObject("scripting.dictionary")
- SQL = "SELECT * FROM [Excel 12.0;Database=" & myPath & p & ";].[Sheet1$a2:d]"
- arr = cnn.Execute(SQL).GetRows
- ReDim brr(1 To UBound(arr, 2) + 1, 0 To 2)
- For i = 0 To UBound(arr, 2)
- If Not d.Exists(arr(1, i)) Then
- m = m + 1
- d(arr(1, i)) = m
- For j = 1 To 2
- brr(m, j) = arr(j, i)
- Next
- Else
- brr(d(arr(1, i)), 2) = brr(d(arr(1, i)), 2) & "," & arr(2, i)
- End If
- Next
- SQL = "SELECT * FROM " & myTable & " WHERE 1=2"
- Set rs = New ADODB.Recordset
- rs.Open SQL, cnn, adOpenKeyset, adLockOptimistic
- For i = 1 To m
- rs.AddNew
- For j = 0 To 1
- rs.Fields(j) = brr(i, j + 1)
- Next
- rs.Update
- Next
- MsgBox " 成功导入 ", vbInformation, " 导入数据库 "
- rs.Close
- cnn.Close
- Set rs = Nothing
- Set cnn = Nothing
- Set Cat = Nothing
- End Sub
复制代码 |
|