Create separate row for each item when merging multiple workbooks

后端 未结 2 1306
梦如初夏
梦如初夏 2021-01-29 07:20

I have several hundred spreadsheets that I would like to combine into a single master sheet. Each spreadsheet contains general description information in several sells, and the

2条回答
  •  轻奢々
    轻奢々 (楼主)
    2021-01-29 07:44

    I'm slightly worried because the headings you seem to be writing to the master sheet don't seem to line up with the data, and because you seem to be only copying Range("A11, A5, B5") from the top part of each sheet but your images show 5 fields being taken from the top, but I think you can replace your For FNum loop with the following:

    For FNum = LBound(MyFiles) To UBound(MyFiles)
        Set mybook = Nothing
        On Error Resume Next
        Set mybook = Workbooks.Open(MyPath & MyFiles(FNum))
        On Error GoTo 0
    
        If Not mybook Is Nothing Then
            With mybook.Worksheets(1)
                Set SourceRange = .Range("A13:D" & .Range("A13").End(xlDown).Row)
    
                SourceRcount = SourceRange.Rows.Count
    
                If rnum + SourceRcount >= BaseWks.Rows.Count Then
                    MsgBox "There are not enough rows in the target worksheet."
                    BaseWks.Columns.AutoFit
                    mybook.Close savechanges:=False
                    GoTo ExitTheSub
                Else
    
                    ' Copy the file name in column A.
                    BaseWks.Cells(rnum + 1, "A").Resize(SourceRcount).Value = MyFiles(FNum)
                    ' Copy information such as date/time started, start/final temp, and Batch ID
                    BaseWks.Cells(rnum + 1, "B").Resize(SourceRcount).Value = .Range("A4").Value
                    BaseWks.Cells(rnum + 1, "C").Resize(SourceRcount).Value = .Range("B4").Value
                    BaseWks.Cells(rnum + 1, "D").Resize(SourceRcount).Value = .Range("A5").Value
                    BaseWks.Cells(rnum + 1, "E").Resize(SourceRcount).Value = .Range("A5").Value
                    BaseWks.Cells(rnum + 1, "F").Resize(SourceRcount).Value = .Range("A11").Value
                    'Copy main data
                    BaseWks.Cells(rnum + 1, "G").Resize(SourceRcount, SourceRange.Columns.Count).Value = SourceRange.Value
    
                    rnum = rnum + SourceRcount
                End If
            End With
        End If
        mybook.Close savechanges:=False
    Next FNum
    

提交回复
热议问题