This lDestLastRow=Sheet1.Cells(1,1).CurrentRegion.Row+1
does not find the very last row of the entire sheet. Therefore you should use wsDest.UsedRange.Find("*", , , , xlByRows, xlPrevious).Row
Don't name your variable lDestLastRow
and then put the row number of the last row + 1
that is very confusing. Name your variable according to what is in there eg lDestNextFreeRow
Fix your typos in the code .Sheets(1)Range(B:E)
should be .Sheets(1).Range("B:E")
and so on.
If you copy full columns Range("B:E")
you can only past them in full columns otherwise you exceed the maximum rows of the sheet. Therefore limit the rows to your actual data instead of copying full columns.
Range("B1:E1").Resize(RowSize:=lSrcLastRow)
This will use the first cells of column B
to E
and then resize to the amount of rows where data was found.
Something like the following should work:
Option Explicit
Public Sub get_data_from_file()
Dim wsDest As Worksheet
Set wsDest = Workbooks("Test.xslm").Worksheets("Input Sheet")
Dim lDestNextFreeRow As Long 'find next free row in destination sheet
lDestNextFreeRow = wsDest.UsedRange.Find("*", , , , xlByRows, xlPrevious).Row + 1
Dim FileToOpen As Variant
FileToOpen = Application.GetOpenFilename(Title:="Browse for your file and input range", FileFilter:="Excel Files (*xls*),*xls*")
If FileToOpen <> False Then
Dim OpenBook As Workbook
Set OpenBook = Application.Workbooks.Open(FileToOpen)
Dim lSrcLastRow As Long 'find last used row in the source sheet
lSrcLastRow = OpenBook.Sheets(1).UsedRange.Find("*", , , , xlByRows, xlPrevious).Row
OpenBook.Sheets(1).Range("B1:E1").Resize(RowSize:=lSrcLastRow).Copy
wsDest.Range("A" & lDestNextFreeRow).PasteSpecial xlPasteValues
OpenBook.Sheets(1).Range("G1:H1").Resize(RowSize:=lSrcLastRow).Copy
wsDest.Range("E" & lDestNextFreeRow).PasteSpecial xlPasteValues
OpenBook.Sheets(1).Range("M1").Resize(RowSize:=lSrcLastRow).Copy
wsDest.Range("G" & lDestNextFreeRow).PasteSpecial xlPasteValues
End If
End Sub
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…