作者:绿色风
分类:
时间:2022-08-17
浏览:136
楼主 芐雨 |
原案例:附件中有很多工作簿,利用ADO的SQL union all语句把路径下所有工作簿的内容合并到一个工作表中,因工作簿中可能存在没有内容的工作表,select * from 空表时就会出现错误。 解决思路: 在语句执行前加入 On Error Resume Next语句,使得程序忽略”运行时错误“而继续执行,当该语句初执行之后,则可以通过判断Err对象的Number属性是否为0而得知工作表是否为空表。
代码如下:(注释部分)
- Sub 批量合并()
- Dim cnn As Object, rs As Object, SQL$, Mypath$, MyFile$, m&, sht As Worksheet, sh As Worksheet, Temp$
- On Error Resume Next '****错误时跳过*****
- With Application.FileDialog(msoFileDialogFolderPicker)
- .InitialFileName = ThisWorkbook.Path & "\"
- If .Show = False Then Exit Sub
- Mypath = .SelectedItems(1) & "\"
- End With
- Application.ScreenUpdating = False
- Application.DisplayAlerts = False
- Set sht = ActiveSheet
- Set sh = Sheets.Add
- MyFile = Dir(Mypath & "*.xlsx")
- sht.Range("A2:N1048576").ClearContents
- Do While MyFile <> ""
- If InStr(MyFile, ThisWorkbook.Name) = 0 Then
- Set cnn = CreateObject("ADODB.Connection")
- cnn.Open "Provider=Microsoft.ACE.OLEDB.12.0;Extended Properties=Excel 12.0;Data Source=" & Mypath & MyFile
- Set rs = cnn.OpenSchema(20) '
- Do Until rs.EOF
- If rs.Fields("TABLE_TYPE") = "TABLE" Then
- s = Replace(rs("TABLE_NAME").Value, "'", "")
- If Right(s, 1) = "$" Then
- m = m + 1
- If m > 49 Then
- sht.Range("A1048576").End(xlUp).Offset(1).CopyFromRecordset cnn.Execute(SQL)
- m = 1
- SQL = ""
- End If
- Temp = "select top 1 * from [Excel 12.0;Database=" & Mypath & MyFile & ";].[" & s & "A:N] where 车间 IS NOT NULL "
- sh.Range("A1").CopyFromRecordset cnn.Execute(Temp) '****对象中的内容复制到工作表****
- If Err.Number = 0 Then '****等于0时,即上一行代码没有出错,可以写入SQL语句中,反之跳过****
- If Len(SQL) Then SQL = SQL & " union all "
- SQL = SQL & "select * from [Excel 12.0;Database=" & Mypath & MyFile & ";].[" & s & "A:N] where 车间 IS NOT NULL "
- End If
- Err.Clear
- End If
- End If
- rs.MoveNext
- Loop
- End If
- MyFile = Dir()
- Loop
- If Len(SQL) Then sht.Range("A1048576").End(xlUp).Offset(1).CopyFromRecordset cnn.Execute(SQL)
- rs.Close
- cnn.Close
- Set rs = Nothing
- Set cnn = Nothing
- sh.Delete
- Application.ScreenUpdating = True
- Application.DisplayAlerts = True
- End Sub
知识点: Err对象是存在于Excel程序中的全局对象 ,其伴随着Excel程序而始终存在。该对象记录VBA程序”运行时错误“的信息。 Err对象的Numer属性记录”运行时错误“的错误号。当没有错误发生时,属性为0。当错误发生时,为该错误对应的错误号。 例:
- Sub 利用错误号判断工作表是否存在()
- Dim sht As Worksheet
- Err.Clear '消除现有错误
- On Error Resume Next '忽略错误继续执行
- Set sht = Worksheets(工作表名)
- If Err.Number = 0 Then '判断是否发生错误
- MsgBox "此工作表存在"
- Else
- MsgBox "此工作表不存在"
- End If
- End Sub
附件:
车间收入.zip
|
免责声明
有感于原ExcelTip.Net留存知识的价值及部分知识具有的时间限定性因素,
经与ExcelTip.Net站长Apolloh商议并征得其同意,
现将原属ExcelTip.Net的知识帖采集资料于本站点进行展示,
供有需要的人士查询使用,也慰缅曾经的论坛时代。
所示各个帖子的原作者如对版权有异议,
可与本人沟通提出,或于本站点留言,我们会尽快处理。
在此,感谢ExcelTip.Net站长Apolloh的支持,感谢本站点所有人**绿色风(QQ:79664738)**的支持与奉献,特此鸣谢!
------本人网名**KevinChengCW(QQ:1210618015)**原ExcelTip.Net总版主之一