3704对象关闭时_对象关闭时,不允许操作,运行时错误3704

这段VBA代码用于批量合并多个Excel文件中的数据。它首先打开一个文件对话框让用户选择文件夹,然后遍历该文件夹中的所有xlsx文件,连接到每个文件的ACE.OLEDB数据源,读取表格数据并将其追加到活动工作簿中。如果表格名以字母F开头或以美元符号结尾,则不进行合并。
摘要由CSDN通过智能技术生成

Sub 合并数据()

Dim cnn As Object, rs As Object

Dim SQL$, MyFile$, s$, m&, n&, t$, i%, z$, v%

With Application.FileDialog(msoFileDialogFolderPicker)

.InitialFileName = ThisWorkbook.Path & ""

If .Show = False Then Exit Sub

MyPath = .SelectedItems(1) & ""

End With

Dim msg As String, nsg As String, BBB As String

Application.ScreenUpdating = False

Set cnn = CreateObject("ADODB.Connection")

Set cat = CreateObject("ADOX.Catalog")

Cells.ClearContents

MyFile = Dir(MyPath & "*.xlsx")

On Error Resume Next

Do While MyFile <> ""

If MyFile <> ThisWorkbook.Name Then

n = n + 1

If n = 1 Then

'cnn.Open "Provider=Microsoft.jet.OLEDB.4.0;Extended Properties=Excel 8.0;Data Source=" & MyPath & MyFile

cnn.Open "Provider=Microsoft.ACE.OLEDB.12.0;Data Source='" & MyPath & MyFile & "';Extended Properties='Excel 12.0 Xml';"

Else

t = "[Excel 12.0;Database=" & MyPath & MyFile & "]."

End If

cat.ActiveConnection = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source='" & MyPath & MyFile & "';Extended Properties='Excel 12.0 Xml';" '"Provider=Microsoft.jet.OLEDB.4.0;Extended Properties=Excel 8.0;Data Source=" & MyPath & MyFile

For Each tb1 In cat.Tables

If tb1.Type = "TABLE" Then

z = ""

z = tb1.Columns(0).Name

If Left$(z, 1) <> "F" Then

s = Replace(tb1.Name, "'", "")

If Right(s, 1) = "$" Then

v = v + 1

If v = 1 Then

Set rs = cnn.Execute("[" & s & "]")

For i = 1 To rs.Fields.Count

Cells(1, i) = rs.Fields(i - 1).Name

Next

End If

m = m + 1

If m > 49 Then

Range("a" & Rows.Count).End(xlUp).Offset(1).CopyFromRecordset cnn.Execute(SQL)

m = 1

SQL = ""

End If

If Len(SQL) Then SQL = SQL & " union all "

SQL = SQL & "select * from " & t & "[" & s & "] "

End If

End If

End If

Next

End If

MyFile = Dir()

Loop

On Error GoTo 0

If Len(SQL) Then Range("a" & Rows.Count).End(xlUp).Offset(1).CopyFromRecordset cnn.Execute(SQL)

cnn.Close

Set cnn = Nothing

Set cat = Nothing

Set tb1 = Nothing

Application.ScreenUpdating = True

End Sub

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值