汇总某文件夹中所有工作薄的第一个工作表的5到最后一行

Sub 汇总工作簿()
    Dim folderPath As String
    Dim fileName As String
    Dim wb As Workbook
    Dim ws As Worksheet
    Dim targetWs As Worksheet
    Dim lastRow As Long
    Dim targetLastRow As Long
    Dim startRow As Long
    Dim fd As fileDialog
    Dim row As Long
    Dim pic As Picture

    On Error GoTo ErrorHandler ' 启用错误处理

    ' 设置目标工作表
    Set targetWs = ThisWorkbook.Sheets(1) ' 假设当前工作簿的第一个工作表为目标工作表

    ' 获取目标工作表的最后一行
    targetLastRow = targetWs.Cells(targetWs.Rows.Count, 1).End(xlUp).Row

    ' 创建文件夹选择对话框
    Set fd = Application.fileDialog(msoFileDialogFolderPicker)
    With fd
        .Title = "选择文件夹"
        .AllowMultiSelect = False
        If .Show <> -1 Then Exit Sub ' 用户取消选择
        folderPath = .SelectedItems(1) & "\"
    End With

    ' 遍历文件夹中的所有文件
    fileName = Dir(folderPath & "*.xls*")
    Do While fileName <> ""
        ' 打开工作簿
        On Error Resume Next ' 暂时忽略错误
        Set wb = Workbooks.Open(folderPath & fileName)
        If Err.Number <> 0 Then
            MsgBox "无法打开文件: " & folderPath & fileName & vbCrLf & "错误: " & Err.Description, vbExclamation
            Err.Clear
            GoTo NextFile
        End If
        On Error GoTo ErrorHandler ' 恢复错误处理

        ' 设置第一个工作表
        Set ws = wb.Sheets(1)

        ' 获取第一个工作表的最后一行
        lastRow = ws.Cells(ws.Rows.Count, 1).End(xlUp).Row

        ' 如果最后一行小于5,则跳过
        If lastRow >= 5 Then
            ' 设置起始行
            startRow = 5

            ' 遍历每一行,检查是否只有第一列的数据
            For row = startRow To lastRow
                ' 检查每一行是否只有第一列的数据
                If Application.WorksheetFunction.CountA(ws.Rows(row)) > 1 Then
                    ' 复制数据到目标工作表,不复制图片
                    ws.Rows(row).Copy Destination:=targetWs.Cells(targetLastRow + 1, 1)
                    ' 更新目标工作表的最后一行
                    targetLastRow = targetWs.Cells(targetWs.Rows.Count, 1).End(xlUp).Row
                End If
            Next row
        End If

        ' 关闭工作簿
        wb.Close SaveChanges:=False

NextFile:
        ' 获取下一个文件
        fileName = Dir
    Loop

    ' 删除目标工作表中的所有图片
    For Each pic In targetWs.Pictures
        pic.Delete
    Next pic

    MsgBox "汇总完成!"
    Exit Sub

ErrorHandler:
    MsgBox "发生错误: " & Err.Description, vbExclamation
End Sub

  • 5
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值