用VB把多个excel文件的数据顺序拷到一个excel中

是给朋友整理实验数据用的,两个小需求:

一、要第一列是数据序号,且多个文件数据拷到目的文件的时候数据序号要按顺序排列;

二、每个文件可能有多个worksheet,都要拷贝到目标文件里面。

对于office2003以前的excel,是支持Application.FileSearch的,实现代码如下:

Sub test()

Dim i As Integer,iRow As Integer
Dim strPath As String
Dim TheSheet As Worksheet
iRow = 1
Set TheSheet = ActiveWorkbook.Worksheets("sheet1")
strPath = "D:/Macro/testtest"

With Application.FileSearch
.LookIn = strPath
.SearchSubFolders = True
.Filename = "*.*"
If .Execute > 0 Then
For i = 1 To .FoundFiles.Count
'Range("A" & i) = .FoundFiles(i)
Workbooks.Open (.FoundFiles(i))
For j = 1 To ActiveWorkbook.Worksheets.Count
'ActiveWorkbook.Worksheets(i).Cells(1,1).Value = "a"
ActiveWorkbook.Worksheets(j).UsedRange.copy

TheSheet.Activate
While TheSheet.Range("a" & iRow).Value <> ""
TheSheet.Cells(iRow,1) = iRow
iRow = iRow + 1
Wend

TheSheet.Range("A" & iRow).Select
ActiveSheet.Paste
ActiveWorkbook.Save

Next j

Workbooks(Workbooks.Count).Close
Next i
End If
End With

End Sub

--------------------------------------------------------------------------------------

对于Office2007的用户,Application.FileSearch不支持了,修改后的代码如下:

Sub test()

Dim i As Integer,iRow As Integer
Dim strPath,Filename,Search_Fullname As String
Dim TheSheet,CurrentSheet As Worksheet
Dim Coll_Docs As New Collection
Dim activeSheetName As String
iRow = 1
Set TheSheet = ActiveWorkbook.Worksheets("sheet1")
strPath = "D:/Macro/testtest"
Filename = "*.xls"
Set Coll_Docs = nothing

DocName = Dir(strPath & "/" & Filename)

Do Until DocName = ""
Coll_Docs.Add Item:=DocName
DocName = Dir
Loop

For i = Coll_Docs.Count To 1 Step -1
Search_Fullname = strPath & "/" & Coll_Docs(i)
Workbooks.Open (Search_Fullname)
For j = 1 To ActiveWorkbook.Worksheets.Count Step 1
If j = 1 Then
activeSheetName = "sheet" & j
Set CurrentSheet = ActiveWorkbook.Worksheets(activeSheetName)
End If
CurrentSheet.Activate
ActiveWorkbook.Worksheets(j).UsedRange.copy
TheSheet.Activate
While TheSheet.Range("a" & iRow).Value <> ""
TheSheet.Cells(iRow,1) = iRow
iRow = iRow + 1
Wend

TheSheet.Range("A" & iRow).Select
ActiveSheet.Paste
ActiveWorkbook.Save

Next j

Workbooks(Workbooks.Count).Close
Next i

End Sub

相关文章

Format[$] ( expr [ , fmt ] ) format 返回变体型 format$ 强...
VB6或者ASP 格式化时间为 MM/dd/yyyy 格式,竟然没有好的办...
在项目中添加如下代码:新建窗口来显示异常信息。 Namespace...
转了这一篇文章,原来一直想用C#做k3的插件开发,vb没有C#用...
Sub 分列() ‘以空格为分隔符,连续空格只算1个。对所选...
  窗体代码 1 Private Sub Text1_OLEDragDrop(Data As Dat...