|
本帖最后由 Henry D. Sy 于 2017-7-8 09:35 编辑
利用Excel QueryTable导出数据无法彻底删除查询表
有时可以删除,有时又不能删除
特意把导入分成两种情况
最开始时,只写了第一种导出方式,结果没有删除成功
增加了第二种导入方式,发现第一种方式下,删除成功,而第二种却不成功
把两种情况分开写(也就是不在一个模块种),结果是有时成功,有时不成功,
不知道问题出在哪里,搞了半天也没搞明白.
(如果保留查询表,每次打开该Excel文件,总会提醒更新或者启用,除非选项里设为接受所有的连接)
代码如下,请大家指教指教
- Private Sub Command0_Click()
- Dim xlApp As New Excel.Application
- Dim xlBook As New Excel.Workbook
- Dim xlSheet As Excel.Worksheet
- Dim xlQuery As Excel.QueryTable
- Dim i As Long
- Dim intRows As Long
- Dim rs As New ADODB.Recordset
- Dim rst As New ADODB.Recordset
- Dim sSQL As String
- xlApp.DisplayAlerts = False
- Set xlBook = xlApp.Workbooks.Open(CurrentProject.Path & "\test.xls")
- xlBook.SaveAs (CurrentProject.Path & "" & Format(Now, "yyyymmddnn") & ".xls")
- rs.CursorLocation = adUseClient
- rst.CursorLocation = adUseClient
- '------------------------------------
- '分成两种情况进行测试删除查询表的结果
- '------------------------------------
- '---------------------------------
- '1.直接将记录导入到Excel工作表A中
- '---------------------------------
- Set xlSheet = xlBook.Worksheets("A")
- rs.Open "A", CurrentProject.Connection, adOpenKeyset, adLockReadOnly
- Set xlQuery = xlSheet.QueryTables.Add(rs, xlSheet.Range("A1"))
- xlQuery.Refresh
- xlQuery.Delete '结果删除成功
- Set xlQuery = Nothing
- rs.Close
- '------------------------------------
- '2.特意采用循环导入工作表B,并分成小表
- '------------------------------------
- intRows = 1
- Set xlSheet = xlBook.Worksheets("B")
- sSQL = "SELECT DISTINCT PO FROM A ORDER BY PO"
- rs.Open sSQL, CurrentProject.Connection, adOpenKeyset, adLockReadOnly
- Do While Not rs.EOF
- sSQL = "SELECT * FROM A WHERE PO='" & rs.Fields("PO") & "'"
- rst.Open sSQL, CurrentProject.Connection, adOpenKeyset, adLockReadOnly
- i = rst.RecordCount
- Set xlQuery = xlSheet.QueryTables.Add(rst, xlSheet.Range("A" & intRows))
- xlQuery.Refresh
- xlQuery.Delete '结果没有删除了查询表
- Set xlQuery = Nothing
- intRows = intRows + i + 3
- rst.Close
- rs.MoveNext
- Loop
- rs.Close
- xlBook.Save
- xlApp.DisplayAlerts = True
- Set rst = Nothing
- Set rs = Nothing
- xlApp.Visible = True
- Set xlSheet = Nothing
- Set xlBook = Nothing
- Set xlApp = Nothing
- End Sub
复制代码
结果在Excel里发现,部分连接存在,没有完全删除!
|
本帖子中包含更多资源
您需要 登录 才可以下载或查看,没有帐号?注册
x
|