Excel VBA, paste from multiple files - vba

I have following issues with this code.
it wont run when i open excel.
And
It will not paste from my files correctly. i want it to step to the last row and paste my info, then step down and paste from the second file, and so on.
any ideas?
Private Sub Workbook_Open()
Dim FolderPath As String
Dim FileName As String
FolderPath = "D:\excelprojekt\"
FileName = Dir(FolderPath & "*.xlsx")
Dim lastrow As Long
Dim lastcolumn As Long
Do While FileName <> ""
Workbooks.Open (FolderPath & FileName)
lastrow = ActiveSheet.Cells(Rows.Count, 1).End(xlUp).Row
lastcolumn = ActiveSheet.Cells(1, Columns.Count).End(xlToLeft).Column
Range(Cells(1, 1), Cells(lastrow, lastcolumn)).Copy
Application.DisplayAlerts = False
ActiveWorkbook.Close
With ActiveSheet
lastrow = .Cells(.Rows.Count, "A").End(xlUp).Row
ActiveCell.Offset(rowOffset:=2, columnOffset:=0).Activate
ActiveSheet.PasteSpecial
End With
FileName = Dir
Loop
End Sub

I think it's possible to maintain copied data after closing a workbook, but there's no reason to do that here. If you qualify your workbook references you can copy from one workbook to another while both are open. If you know what sheets you want to be copying from and into, you should probably explicitly reference them instead of using ActiveSheet as well (I think ActiveSheet will be whatever sheet was active when the file was last saved when opening a file)
Private Sub Workbook_Open()
Dim FolderPath As String
Dim FileName As String
FolderPath = "D:\excelprojekt\"
FileName = Dir(FolderPath & "*.xlsx")
Dim lastrow As Long
Dim lastcolumn As Long
Dim wbOpened as Workbook
Do While FileName <> ""
Set wbOpened = Workbooks.Open(FolderPath & FileName)
With wbOpened.ActiveSheet
lastrow = .Cells(Rows.Count, 1).End(xlUp).Row
lastcolumn = .Cells(1, Columns.Count).End(xlToLeft).Column
.Range(.Cells(1, 1), .Cells(lastrow, lastcolumn)).Copy
End With
ThisWorkbook.ActiveSheet.Cells(Rows.Count, 1).End(xlUp).Offset(2).PasteSpecial
Application.DisplayAlerts = False
wbOpened.Close
FileName = Dir
Loop
End Sub

Related

Saving a xlsx file in a particular folder

I am trying to copy the content from source workbook to a new workbook and save it in xlsx format in a specified folder.
I am trying the below code and I get application defined error in the Last line of the code, where I am trying to save my new workbook as .xlsx
Also, It takes long time approx. 5min for this small piece of code.
Sub newWB()
Dim myWksht As String
Dim newWB As Workbook
Dim MyBook As Workbook
Dim i As Integer, j As Integer
Dim LastRow As Long, totalrows As Long
Dim path1, path2 As String
path1 = ThisWorkbook.Path
path2 = path1 & "\Tru\Sq\"
Set newWB = Workbooks.Add
With ThisWorkbook.Worksheets("Pivottabelle")
LastRow = .Cells(.Rows.Count, "A").End(xlUp).Row
End With
With newWB.Sheets("Sheet1")
.Name = "PivotTable"
j = .Cells(.Rows.Count, "A").End(xlUp).Row + 1
End With
With Worksheets("Pivottabelle")
For i = 1 To LastRow
ThisWorkbook.Sheets("Pivottabelle").Range("A1:Y400").Copy: newWB.Sheets("PivotTable").PasteSpecial
Next i
End With
With newWB.Worksheets("PivotTable")
totalrows = .Cells(.Rows.Count, "A").End(xlUp).Row
For i = totalrows To 2 Step -1
If .Cells(i, 8).Value <> "TRU" Then
Cells(i, 8).EntireRow.Delete
End If
Next
newWB.SaveAs Filename:=path2 & ".xlsx"
End With
End Sub
This should show all the improvements from the comments (plus some more) …
It can be that you run into issues when saving because this
DestinationPath = ThisWorkbook.Path & "\Tru\Sq\"
only works if the macro containing workbook is already saved. Otherwise ThisWorkbook.Path is empty. And you probably need to be sure that these subfolders already exist.
Option Explicit 'force variable declare
Public Sub AddNewWorkbook() 'sub and newWB had the same name (no good practice)
'Dim myWksht As String 'not used therefore can be removed
Dim newWB As Workbook
'Dim MyBook As Workbook 'not used therefore can be removed
'Dim i As Integer, j As Integer
Dim i As Long, j As Long 'use long instead of integer whenever possible
'see https://stackoverflow.com/a/26409520/3219613
Dim LastRow As Long, totalrows As Long
'Dim path1, path2 As String 'always specify a type for every variable
Dim DestinationPath As String 'we only need one path
DestinationPath = ThisWorkbook.Path & "\Tru\Sq\"
'path2 = path1 & "\Tru\Sq\" ' can be reduced to one path
Set newWB = Workbooks.Add
With ThisWorkbook.Worksheets("Pivottabelle")
LastRow = .Cells(.Rows.Count, "A").End(xlUp).Row
End With
With newWB.Sheets("Sheet1")
.Name = "PivotTable"
j = .Cells(.Rows.Count, "A").End(xlUp).Row + 1
End With
'With Worksheets("Pivottabelle") 'unecessary with (not used at all)
'For i = 1 To LastRow 'unecessary loop
ThisWorkbook.Sheets("Pivottabelle").Range("A1:Y400").Copy
newWB.Sheets("PivotTable").PasteSpecial
'Next i
'End With
With newWB.Worksheets("PivotTable")
totalrows = .Cells(.Rows.Count, "A").End(xlUp).Row
For i = totalrows To 2 Step -1
If .Cells(i, 8).Value <> "TRU" Then
.Cells(i, 8).EntireRow.Delete 'was missing a . before Cells(i, 8).EntireRow.Delete
End If
Next
newWB.SaveAs Filename:=DestinationPath & "FILENAME" & ".xlsx" 'was missing a filename
End With
End Sub

How can I copy data from specific worksheet of a workbook to another with the same worksheet name?

I have 7 productivity files which I need to copy the data from the sheet titled worktracker and paste these in the worktracker sheet in the masterfile, but I'm getting:
Run-time error 1004
Method Range of object_Worksheet failed.
Private Sub CommandButton1_Click()
Dim file As String
Dim myPath As String
Dim wb As Workbook
Dim rng As Range
Dim lastrow As Long, lastcolumn As Long
Dim wbMaster As Workbook
Set wbMaster = Workbooks("WorkTracker_Master.xlsm")
Set rng = wbMaster.Sheets("WorkTracker").Range("A4:W4")
myPath = "\\BMGSMP1012\GBDMC_Team$\GBDM_ContentManagement\+CM_Reports\Productivity Reports\FY18\"
file = Dir(myPath & "*.xls*")
While (file <> "")
Set wb = Workbooks.Open(myPath & file)
lastrow = wb.Worksheets("WorkTracker").Cells(Rows.Count, 1).End(xlUp).Row
lastcolumn = wb.Worksheets("WorkTracker").Cells(1, Columns.Count).End(xlToLeft).Column
Range(Cell(2, 1)(lastrow, lastcolumn)).Copy
Application.DisplayAlerts = False
ActiveWorkbook.Close
erow = WorkTracker.Cells(Rows.Count, 1).End(xlUp).Offset(1, 0).Row
ActiveSheet.Paste Destination = Worksheets("WorkTracker").Range(Cells(erow, 1), Cells(erow, 4))
wb.Close SaveChanges:=True
Set wb = Nothing
file = Dir
Wend
Application.CutCopyMode = False
End Sub
You need to fully qualify all your objects, a comfortable and easy way, is to seperate each Workbook by using a nested With statement.
Also, as #YowE3K already mentioned in the comments above, you have a syntax error when defining the copied Range.
Try the code below, inside your While (file <> "") loop, after you Set wb = Workbooks.Open(myPath & file) :
With wb.Worksheets("WorkTracker")
lastrow = .Cells(.Rows.Count, 1).End(xlUp).Row
lastcolumn = .Cells(1, .Columns.Count).End(xlToLeft).Column
.Range(.Cells(2, 1), .Cells(lastrow, lastcolumn)).Copy
End With
With wbMaster.Worksheets("WorkTracker")
' get first empty row in column "A"
erow = .Cells(.Rows.Count, 1).End(xlUp).Offset(1, 0).Row
' paste in the first empty row
.Range("A" & erow).PasteSpecial
End With
wb.Close SaveChanges:=True
Set wb = Nothing

Copy-paste special VBA does not work

I am trying to copy-paste special values and formatting from multiple workbooks into a master spreadsheet. The number of columns is the same in the source and destination and the number of rows varies.
I read the other threads on this and tried multiple ways (including defining a range in the destination file) but I still cannot make the paste special work. Below is my code:
Sub mergefiles()
Dim folderpath As String
Dim filepath As String
Dim filename As String
Dim erow As Long
folderpath = "D:\Test\"
filepath = folderpath & "*.xls*"
filename = Dir(filepath)
Dim lastrow As Long, lastcolumn As Long
Do While filename <> ""
Workbooks.Open (folderpath & filename)
Worksheets("EmplOffers").ShowAllData
lastrow = ActiveSheet.Cells(Rows.Count, 3).End(xlUp).Row
lastcolumn = ActiveSheet.Cells(6, Columns.Count).End(xlToLeft).Column
Range(Cells(6, 3), Cells(lastrow, lastcolumn)).Copy
Application.DisplayAlerts = False
ActiveWorkbook.Close
erow = Worksheets("EmplOffers").Cells(Rows.Count, 3).End(xlUp).Offset(1, 0).Row
Worksheets("EmplOffers").Range(Cells(erow, 3), Cells(erow, 20)).PasteSpecial=:xlPasteValuesAndNumberFormats
filename = Dir
Loop
Application.DisplayAlerts = True
End Sub
Thanks a lot!
Try adjusting the paste call:
Worksheets("EmplOffers").Range(Cells(erow, 3).Address).PasteSpecial Operation:=xlPasteValuesAndNumberFormats
A named parameter should precede :=
Change
Worksheets("EmplOffers").Range(Cells(erow, 3), Cells(erow, 20)).PasteSpecial=:xlPasteValuesAndNumberFormats
To:
Worksheets("EmplOffers").Range(Cells(erow, 3), Cells(erow, 20)).PasteSpecial Paste:=xlPasteValuesAndNumberFormats

Combine copied data into a single worksheet

I am currently use a VBA script to combine data from multiple sheets and workbooks into a a new workbook. Currently the script does this but creates multiple sheets in the destination workbook. Is it possible to just has destination be a single sheet?
Sub copydata()
Dim FolderPath As String, FilePath As String, FileName As String
FolderPath = "C:\attach\"
FilePath = FolderPath & "*.xlsx"
FileName = Dir(FilePath)
Dim erow As Long, lastrow As Long, lastcolumn As Long
'loops through directory as long as it is not blank and defines files as workbooks.
Do While FileName <> ""
Dim wb As Workbook
Set wb = Workbooks.Open(FolderPath & FileName)
'nested loop for sheets in workbooks
For counter = 3 To 9
'Sheets(“Sheet1”).Select
wb.Worksheets(counter).Activate
lastrow = ActiveSheet.Cells(Rows.count, 1).End(xlUp).Row
lastcolumn = ActiveSheet.Cells(1, Columns.count).End(xlToLeft).Column
Range(Cells(2, 1), Cells(lastrow, lastcolumn)).Copy
'Sheets("Sheet1").Select
Workbooks("ZMasterFile.xlsx").Worksheets(counter).Activate
erow = ActiveSheet.Cells(Rows.count, 1).End(xlUp).Offset(1, 0).Row
Cells(erow, 1).Select
ActiveSheet.Paste
Next
wb.Close savechanges:=False
FileName = Dir
Loop
erow = ActiveSheet.Cells(Rows.count, 1).End(xlUp).Offset(1, 0).Row
Cells(erow, 1).Select
This line might causing you the trouble.
'Sheets("Sheet1").Select
Workbooks("ZMasterFile.xlsx").Worksheets(counter).Activate
On the secound line, you are activating worksheet(counter)
I think you should put Worksheet("Sheet1") if you want all the datas to be in same sheet.
Of course. Probably your best bet is to install the AddIn you find from the link below.
http://www.rondebruin.nl/win/addins/rdbmerge.htm
That tool is very useful! Try it and you'll see!
Also, see the link below. You will see all the code exposed there, so it's a great learning example.
http://www.rondebruin.nl/win/s3/win008.htm

Import sheets from different workbooks does not work due to sheet name?

Code works fine as it imports data from sheets of different workbooks with name Trippings_15.
But i want the program to import sheets with name Trippings_Jan_15, Trippings_Feb_15, Trippings_March_15, etc from workbook 1,2,3 respectively when i use Trippings_15 in code or I can simply give the absolute address of that sheet irrespective of tab name like sheet7 from all workbooks.
I am making a database where all monthly trippings of 2015 will be shown a single sheet.
Sub copyDataFromMultipleWorkbooksIntoMaster()
Dim FolderPath As String, Filepath As String, Filename As String
FolderPath = "D:\Copy Multiple Excel to One master\"
Filepath = FolderPath & "*.xls*"
Dim lastRow As Long, lastCol As Long, eRow As Long
Dim wb As Workbook, ws As Worksheet
Application.DisplayAlerts = False
Filename = Dir(Filepath)
Do While Filename <> ""
eRow = Sheet1.Cells(Rows.count, 1).End(xlUp).Offset(1, 0).Row
Set wb = Workbooks.Open(FolderPath & Filename)
On Error Goto NextFile
Set ws = wb.Worksheets("Trippings_15")
With ws
lastRow = .Cells(.Rows.count, 1).End(xlUp).Row
lastCol = .Cells(1, .Columns.count).End(xlToLeft).Column
.Range(.Cells(5, 1), .Cells(lastRow, lastCol)).Copy
Sheet1.Cells(eRow, 1).PasteSpecial xlPasteValues
End With
NextFile:
On Error Goto 0
wb.Close False
Filename = Dir
Loop
Application.DisplayAlerts = True
End Sub
Try this. The logic here is that you predefine the months which you will insert in the "Trippings_15" string. Also, add a function to test whether sheet exists, instead of using the clunky On Error Resume Next
Sub copyDataFromMultipleWorkbooksIntoMaster()
Dim FolderPath As String, Filepath As String, Filename As String
'### DEFINE YOUR BASE STRING TO BE UPDATED WITH EACH MONTH
Dim baseSheetName$
baseSheetName = "Trippings_{}_15"
Dim sheetName as String 'This will be updated later...
'### DEFINE AN ARRAY OF MONTHS
Dim months, m
months = Array("JAN","FEB","MAR","APR","MAY","JUN","JUL","AUG","SEP","OCT","NOV","DEC")
FolderPath = "D:\Copy Multiple Excel to One master\"
Filepath = FolderPath & "*.xls*"
Dim lastRow As Long, lastCol As Long, eRow As Long
Dim wb As Workbook, ws As Worksheet
Application.DisplayAlerts = False
Filename = Dir(Filepath)
Do While Filename <> ""
eRow = Sheet1.Cells(Rows.count, 1).End(xlUp).Offset(1, 0).Row
Set wb = Workbooks.Open(FolderPath & Filename)
For Each m in months '## Iterate over each month in your array
sheetName = Replace(baseSheetName,"{}",m) '## this is the month sheet name like "Trippings_Jan_15", etc.
If SheetExists(wb, sheetName) Then '## Check whether this sheet exists before tryingto use it
Set ws = wb.Worksheets(sheetName)
With ws
lastRow = .Cells(.Rows.count, 1).End(xlUp).Row
lastCol = .Cells(1, .Columns.count).End(xlToLeft).Column
.Range(.Cells(5, 1), .Cells(lastRow, lastCol)).Copy
Sheet1.Cells(eRow, 1).PasteSpecial xlPasteValues
End With
End If
Next m
wb.Close False
Filename = Dir
Loop
Application.DisplayAlerts = True
End Sub
Here is the function SheetExists:
Function SheetExists(wb as Workbook, s as String)
Dim ws as Worksheet
Dim ret as Boolean
For Each ws in wb.Worksheets
If ws.Name = s Then
ret = True
Exit For
End If
Next
SheetExists = ret
End Function