Excel交流网
  • 设为首页|收藏本站|手机版
  • Excel-教程-技巧-培训视频

  • 网站首页
  • Excel教程
  • 新闻动态
  • Excel资源
  • 关于我们

Excel教程

Excel操作
Excel函数
Excel图表
Excel VBA
Excel 行业应用

联系方式

Excel中交流网 联系方式

QQ:18449932 


网  址:www.excel-cn.com  

当前位置:网站首页 > Excel教程 > Excel VBA
Excel VBA

excel vba实现将多个文件内容复制汇总到一个Excel文件中

在论坛上看到有网友问到如何把多个数据同时导出追加到同到Excel中。这里写了几个函数。复制到宏命令代码里面,执行宏即可实现。

功能:遍历用户指定的文件夹,把文件夹中所有的excel文件的第一个表格的数据复制到本excel文件中。注意,每个excel文件中有效数据行的判断标准是A列的最后一个有数据的单元格的行号,比如A列到第10行结束,B列到第11行结束,那么程序将不会复制第11行。


效果图:

合并.gif 


详细源码:

Sub combine()
    Dim folder As String
    Dim count As Integer
        
    folder = ChooseFolder()
    
    count = combineFiles(folder, "xls")
    'count = count + combineFiles(folder, "xlsx")

End Sub

'整合文件
Function combineFiles(folder, appendix)
    Dim MyFile As String
    Dim s As String
    Dim count, n, copiedlines As Integer
    
    MyFile = Dir(folder & "\*." & appendix)
    count = count + 1
    n = 2
    Do While MyFile <> ""
        copiedlines = CopyFile(folder & "\" & MyFile, 2, n)
        If copiedlines > 0 Then
            n = n + copiedlines
            count = count + 1
        End If
        MyFile = Dir
    Loop
    combineFiles = count
End Function

'复制数据
Function CopyFile(filename, srcStartLine, dstStartLine)

    Dim book As Workbook
    Dim sheet As Worksheet
    Dim rc As Integer
    
    CopyFile = 0
    
    If filename = (ThisWorkbook.Path & "\" & ThisWorkbook.Name) Then
        Exit Function
    End If
    
    Set book = Workbooks.Open(filename)
    Set sheet = book.Sheets(1) '使用第一个sheet
    rc = sheet.Range("A65536").End(xlUp).Row
    If rc >= srcStartLine Then
        sheet.Rows(srcStartLine & ":" & rc).copy ThisWorkbook.Sheets(1).Range("A" & dstStartLine) '复制到指定位置
        CopyFile = rc - srcStartLine + 1
    End If
    book.Close

End Function

'选择文件夹
Function ChooseFolder() As String
    Dim dlgOpen     As FileDialog

    Set dlgOpen = Application.FileDialog(msoFileDialogFolderPicker)
    With dlgOpen
        If .Show = -1 Then
            ChooseFolder = .SelectedItems(1)
        End If
    End With
    Set dlgOpen = Nothing
End Function


参考至:oceanking(博客园)

点击次数:  更新时间:2017-09-11 17:10:26  【打印此页】  【关闭】
上一条:Excel在有序无序排列中为相同的内容添加相同编号  下一条:Excel条件格式和单选控件动态设置折线图
本站动态|在线留言|在线反馈|友情链接|会员中心|站内搜索|网站地图|网站管理

中山市天鸣科技发展有限公司 版权所有 1999-2024 粤ICP备10043721号

QQ:18449932

免费Excel教程、Excel技巧、Excel培训、Excel函数公式、Excel图表、Excel VBA

Excel教程|Excel技巧|Excel培训|Excel函数公式|Excel图表|VBA

Powered by MetInfo 5.3.12 ©2008-2026  www.metinfo.cn