Hi I wonder whether someone may be able to help please.
I'm trying to put together a script which allows the user to select multiple Excel files and paste them into a 'Master' Excel sheet. I've been working with some code that I found on this site here http://www.ozgrid.com/forum/showthread.php?t=65860 and the code below is my adaptation of this:
Sub CopyData()
Dim wsT As Worksheet
Dim wsF As Worksheet
Dim lRow(1) As Long
Dim iCol As Integer
Dim sFile As String
sFile = Application.GetOpenFilename("Excel Files (*.xls), *.xls")
If sFile = "False" Then
Exit Sub
End If
Set wsT = ThisWorkbook.Sheets("Combined")
Workbooks.Open sFile
Set wsF = ActiveSheet
'get size of data
lRow(0) = wsF.Cells.Find(What:="*", _
SearchOrder:=xlByRows, _
SearchDirection:=xlPrevious).Row
iCol = wsF.Cells.Find(What:="*", _
SearchOrder:=xlByColumns, _
SearchDirection:=xlPrevious).Column
lRow(1) = wsT.Cells.Find(What:="*", _
SearchOrder:=xlByRows, _
SearchDirection:=xlPrevious).Row + 1
If lRow(1) + lRow(0) > Rows.Count Then
MsgBox "WorkSheet To full to Copy To", vbInformation
Else
wsT.Range("A" & lRow(1) & ":" & Cells(lRow(1) + lRow(0), iCol).Address).Value _
= wsF.Range("A5:" & Cells(lRow(0), iCol).Address).Value
End If
ActiveWorkbook.Close False
End Sub
Display More
The 'Source' & 'Destinantion' Files have a header row in row 4, so by making the changes here
= wsF.Range("A5:" & Cells(lRow(0), iCol).Address).Value
I tell the macro to start to copy from row 5 and this works fine.
The problem I'm having is with how the information is then pasted into the 'Destination File'. The macro correctly pastes the information on the correct row and columns, but no matter which source file I use, the macro pastes 5 extra rows of data at the end of the imported data with every cell content shown as #N/A.
Through many hours of working through this, I've found that the number of erroneous rows derive from these two lines:
This is where the number of rows are set
= wsF.Range("A5:" & Cells(lRow(0), iCol).Address).Value
with the '(lRow(0))' variable being used in this line
wsT.Range("A" & lRow(1) & ":" & Cells(lRow(1) + lRow(0), iCol).Address).Value _
which carries out the 'Paste' command. I know this to be true because if I change A5 to A2 for example, there are 2 rows of erroneous data.
I've tried taking the '(lRow(0))' out of the 'Paste' command line which does solve the problem for the first file that I'm importing. However, if I then try to import a second file I encounter the same problems.
I've been working on this for several days now, but I just can't find the answer.
I just wondered whether someone could perhaps take a look at this please and let me know where I'm going wrong.
Many thanks and regards