|
[广告] Excel易用宝 - 提升Excel的操作效率 · Excel / WPS表格插件 ★ 免费下载 ★ ★ 使用帮助★
本帖最后由 zhaogang1960 于 2015-11-3 15:36 编辑
不需要打开数据源工作簿,这也是ADO大批量处理工作簿的一个优点:- Sub Button1_Click()
- '引用Microsoft ActiveX Data Objects 2.x Library
- '引用Microsoft AD0 Ext 2.8 for DDL and Security
- Dim cnn As New ADODB.Connection
- Dim rs As ADODB.Recordset
- Dim rst As ADODB.Recordset
- Dim cat As New ADOX.Catalog
- Dim tb1 As ADOX.Table
- Dim myPath As String
- Dim myData As String
- Dim p As String
- Dim sh As Worksheet
- Dim SQL As String
- Dim F As Boolean
- myPath = ThisWorkbook.Path & ""
- p = Dir(myPath & "A list *.xls?")
- If p = "" Then
- MsgBox "没有发现数据源工作簿,无需更新。", vbInformation, "提醒"
- Exit Sub
- End If
- myData = myPath & "data.accdb"
- If Dir(myData) = "" Then
- cat.Create "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & myData
- F = True '数据库文件不存在标志
- End If
- cat.ActiveConnection = "Provider=Microsoft.ACE.OLEDB.12.0;Extended Properties=Excel 12.0;Data Source=" & myPath & p
- cnn.Open "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & myData
- For Each tb1 In cat.Tables
- If tb1.Type = "TABLE" Then
- s = Replace(tb1.Name, "'", "")
- If Right(s, 1) = "$" Then
- MyTable = Replace(s, "$", "")
- If Not F Then '数据库文件已经存在,先判断同名数据表是否存在,如果存在就删除它
- Set rs = cnn.OpenSchema(adSchemaTables, Array(Empty, Empty, MyTable, Empty))
- If Not rs.EOF Then
- SQL = "DROP TABLE " & MyTable
- cnn.Execute SQL
- End If
- End If
- Set rst = cnn.Execute("[Excel 12.0;Database=" & myPath & p & ";].[" & s & "]")
- If Not rst.EOF Then
- SQL = "SELECT * INTO " & MyTable & " FROM [Excel 12.0;Database=" & myPath & p & ";].[" & s & "]"
- cnn.Execute SQL
- End If
- End If
- End If
- Next
- MsgBox " 成功导入 ", vbInformation, " 导入数据库 "
- If Not F Then
- rs.Close
- Set rs = Nothing
- End If
- rst.Close
- cnn.Close
- Set rst = Nothing
- Set cnn = Nothing
- Set cat = Nothing
- End Sub
复制代码
|
|