Saving a xlsx file in a particular folder - vba

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

Related

Trying to Pull a specific range of cells from another work book

first timer here, so go easy on me :)
Only been using VBA for a few months on work projects and I have hit a wall with what I can google, figured Id post the problem here.
I have a button that will open a source workbook and copy a specific range of cells from the source workbook to the destination workbook. This range of cells to be copied is determined by a for loop that starts at row 2 and loops to the last row of data. I have this code working in another project, but it appears to not want to run when its targeted at a different workbook.
Appreciate the help and any advice on the code in general would be welcome :)
Private Sub CommandButton1_Click()
Dim lastRow, i, erow As Integer
Dim filename As String
Dim fname As Variant
Dim dwbk, swbk As Workbook
Dim sws, dws As Worksheet
Dim r1 As Range
Set dwbk = ThisWorkbook
Set dws = dwbk.Sheets("Call OFF")
'On Error GoTo ErrHandling
'Application.ScreenUpdating = False
FileArray = Application.GetOpenFilename(Title:="Select file(s)", MultiSelect:=True)
For Each fname In FileArray
Set swbk = Workbooks.Open(fname)
Set sws = swbk.Sheets("Allocations")
lastRow = sws.Range("A" & Rows.Count).End(xlUp).Row
For i = 2 To lastRow
Range(Cells(i, "A"), Cells(i, "B")).Select
Selection.Copy
dwbk.Sheets("CALL OFF").Activate
erow = Worksheets("CALL OFF").Cells(Rows.Count, 2).End(xlUp).Offset(1, 0).Row
Worksheets("CALL OFF").Cells(erow, 2).PasteSpecial xlPasteValues
swbk.Activate
Next i
Next
'Application.ScreenUpdating = True
' End If
'Done:
' Exit Sub
'
'ErrHandling:
' MsgBox "No file selected"
End Sub
Thanks.
You are not specifing the parent on the copy range.
Range(Cells(i, "A"), Cells(i, "B")).Select
Change to:
sws.Range(sws.Cells(i, "A"), sws.Cells(i, "B")).Copy
and remove the Selection.Copy line
But you can speed thing up a little and remove the loop by assigning the values directly:
Private Sub CommandButton1_Click()
Dim lastRow As Long, erow As Long
Dim filename As String
Dim fname As Variant
Dim dwbk As Workbook, swbk As Workbook
Dim sws As Worksheet, dws As Worksheet
Dim r1 As Range
Set dwbk = ThisWorkbook
Set dws = dwbk.Sheets("Call OFF")
'On Error GoTo ErrHandling
'Application.ScreenUpdating = False
FileArray = Application.GetOpenFilename(Title:="Select file(s)", MultiSelect:=True)
For Each fname In FileArray
Set swbk = Workbooks.Open(fname)
Set sws = swbk.Sheets("Allocations")
lastRow = sws.Range("A" & Rows.Count).End(xlUp).Row
erow = dws.Cells(dws.Rows.Count, 2).End(xlUp).Offset(1, 0).Row
dws.Cells(erow, 2).Resize(lastRow - 1, 2).Value = sws.Range(sws.Cells(2, 1), sws.Cells(lastRow, 2)).Value
Next fname
'Application.ScreenUpdating = True
' End If
'Done:
' Exit Sub
'
'ErrHandling:
' MsgBox "No file selected"
End Sub

Excel VBA, paste from multiple files

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

VBA loop throught each cell to copy files

I have an Excel file where columns (icol) each cells contains a path of some files like this :
column A column B column c
P:\Desktop\Source\Test1-folder\file1.txt empty column P:\Desktop\Source\Test1-folder\filetest.txt
P:\Desktop\Source\Test1-folder\file2.txt .....
and I need to loop through these cells to copy files from the cells into destination folder, but i couldn't succeed .Can anyone help how to do it?
Dim strSlash As String, destinationFolder As String
Dim lastcolumn As Long, icol As Long, lastLigne As Long
Dim rngCell As Range, rngFiles As Range
Dim FSO As New FileSystemObject
destinationFolder = "P:\Desktop\folderdestination"
Dim maListe As Object
Dim workboo As Workbook
Dim worksh As Worksheet
Set workboo = Workbooks.Open(P:\Desktop\Source\excelfile.xlsx)
Set worksh = workboo.Worksheets("path_files")
lastcolumn = Cells(1, Cells.Columns.Count).End(xlToLeft).Column
If Dir(destinationFolder, 16) = "" Then MkDir (destinationFolder)
For icol = 1 To lastcolumn Step 2
lastLigne = Cells(Rows.Count, icol).End(xlUp).Row
Set rngFiles = Cells(1, icol).Resize(lastLigne)
For Each rngCell In rngFiles.Cells
If Dir(rngCell.Value) <> "" Then
strFile = Right(rngCell.Value, Len(rngCell.Value) - InStrRev(rngCell.Value, "\"))
If Dir(destinationFolder & "\" & Left(strFile, 5) , 16) = "" Then
FSO.CopyFile rngCell.Value, destinationFolder & "\" & Left(strFile, 5)
End If
End If
Next rngCell
Next icol
end sub
edited to add a check for source file existence
this should do
Option Explicit
Sub main()
Dim strSlash As String, destinationFolder As String
Dim lastcolumn As Long, icol As Long, lastLigne As Long
Dim rngCell As Range, rngFiles As Range
Dim FSO As New FileSystemObject
strSlash = "\"
destinationFolder = "P:\Desktop\folderdestination"
lastcolumn = Cells(1, Cells.Columns.Count).End(xlToLeft).Column
For icol = 1 To lastcolumn Step 2
lastLigne = Cells(Rows.Count, icol).End(xlUp).Row
Set rngFiles = Cells(1, icol).Resize(lastLigne)
For Each rngCell In rngFiles.Cells
If Dir(rngCell.Value) <> "" Then '<~~ check if the source file is actually there!
If Dir(destinationFolder & "\" & Right(rngCell.Value, Len(rngCell.Value) - InStrRev(rngCell.Value, strSlash)), 16) = "" Then
FSO.CopyFile rngCell.Value, destinationFolder & "\" & Right(rngCell.Value, Len(rngCell.Value) - InStrRev(rngCell.Value, strSlash))
End If
End If
Next rngCell
Next icol
End Sub
but it could still be improved to a good extent, exploiting FileSystemObject more thoroughly (which of course needs adding reference to "Microsoft Scripting Runtime" library: Tools->References and then scroll down List Box and select "Microsoft Scripting Runtime" checkbox)

Excel VBA code for Looping through files and copying specific data to one file

I am new to VBA and If anyone can help, I'd greatly appreciate it. I just need help in simple VBA loop in following code.
I am trying to loop through excel files in a folder and copy specific data from source Worksheet in all files to a new workbook (sheet 2). I have a code which does 70% of the job but I am having difficulty in picking some data and copying it in specific format.
Option Explicit
Const FOLDER_PATH = "C:\Temp\" 'REMEMBER END BACKSLASH
Sub ImportWorksheets()
'=============================================
'Process all Excel files in specified folder
'=============================================
Dim sFile As String 'file to process
Dim wsTarget As Worksheet
Dim wbSource As Workbook
Dim wsSource As Worksheet
Dim rowTarget As Long 'output row
Dim FirstRow As Long, LastRow As Long
FirstRow = 1
LastRow = 5
Dim RowRange As Range
rowTarget = 2
'check the folder exists
If Not FileFolderExists(FOLDER_PATH) Then
MsgBox "Specified folder does not exist, exiting!"
Exit Sub
End If
'reset application settings in event of error
On Error Goto errHandler
Application.ScreenUpdating = False
'set up the target worksheet
Set wsTarget = Sheets("Sheet2")
'loop through the Excel files in the folder
sFile = Dir(FOLDER_PATH & "*.xls*")
Do Until sFile = ""
'open the source file and set the source worksheet - ASSUMED WORKSHEET(1)
Set wbSource = Workbooks.Open(FOLDER_PATH & sFile)
Set wsSource = Sheets("DispForm") 'EDIT IF NECESSARY
'import the data
With wsTarget
For Each rw In RowRange
If wsSource.Cells(rw.Row, 1) & wsSource.Cells(rw.Row + 1, 1) = "" Then
Exit For
End If
.Range("A" & rowTarget).Value = wsSource.Range("B1").Value
.Range("B" & rowTarget).Value = wsSource.Cells(rw.Row, 2)
.Range("C" & rowTarget).Value = wsSource.Cells(rw.Row, 4)
.Range("D" & rowTarget).Value = sFile
rowTarget = rowTarget + 1
Next rw
End With
'close the source workbook, increment the output row and get the next file
wbSource.Close SaveChanges:=False
rowTarget = rowTarget + 1
sFile = Dir()
Loop
errHandler:
On Error Resume Next
Application.ScreenUpdating = True
'tidy up
Set wsSource = Nothing
Set wbSource = Nothing
Set wsTarget = Nothing
End Sub
Private Function FileFolderExists(strPath As String) As Boolean
If Not Dir(strPath, vbDirectory) = vbNullString Then FileFolderExists = True
End Function
you only copy one row of data from your source file. so you need either to have a loop inside your file loop to loop all the rows, or to have a range to select all the rows.
try something like the following:
Dim FirstRow As Long, LastRow As Long
FirstRow = 9
LastRow = 100
Set rowRange = wsSource.Range("A" & FirstRow & ":A" & LastRow)
With wsTarget
For Each rw In rowRange
If wsSource.Cells(rw.Row, 2) = "" Then
Exit For
End If
.Range("A" & rowTarget).Value = wsSource.Cells(rw.Row, 2)
.Range("B" & rowTarget).Value = wsSource.Cells(rw.Row, 3)
Next rw
End With

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