VBA to Save in New Directory Depending on Sheet Name - vba

I am trying to prepare a code that opens all files in a folder, checks the name of the sheet in the opened file and, depending on the name of that sheet, re-saves it in to a new folder. However, when I'm trying to add the IF statement to check that the sheet name exists, it's telling me that this Method does not exist. Is anybody able to advise a more appropriate method please?
Dim MyFile As String
MyPath = "Q:\Folder Name1\Folder Name2\Folder Name3\Folder Name4\"
MyFile = Dir(MyPath)
Do While MyFile <> ""
If MyFile Like "*.xlsx" Then
Workbooks.Open MyPath & MyFile
Dim ws1 As Worksheet
Set ws1 = Sheets("Adult_Return")
If ws1.Exists Then
ChDir "Q:\Folder Name1\Folder Name2\Folder Name3\Folder Name4\Return"
ActiveWorkbook.SaveAs Filename:=MyFile & ".xlsx"
Else
ChDir "Q:\Folder Name1\Folder Name2\Folder Name3\Folder Name4\Single"
ActiveWorkbook.SaveAs Filename:=MyFile & ".xlsx"
Thanks.

Create a function:
Function SheetExists(wb As Workbook, sheetName As String)
Dim ws As Worksheet
SheetExists = False
For Each ws In wb.Sheets
If UCase(ws.Name) = UCase(sheetName) Then
SheetExists = True
Exit Function
End If
Next ws
End Function
Call it like this:
Dim wb As Workbook
Set wb = Workbooks.Open(MyPath & MyFile)
If SheetExists(wb, "Adult_Return") Then
...
Btw: You don't have to do the chdir, just put the path in the SaveAs:
wb.SaveAs "Q:\Folder Name1\Folder Name2\Folder Name3\Folder Name4\Single\" & MyFile & ".xlsx
And: Do not forget to close the workbook!

Related

Subscript out of Range VBA Printing

I have a script that will print everything in my "Downloads" folder, the VBA script did work until I added a bit of code to "Fit Columns to Width" so that I could see all data before it printed, now it says "Subscript out of range" once it opens the first file in the "Downloads" folder, I think this is because the "Sheet1" is never called "Sheet1" it is instead named the first 15 characters of the actual file name.
Is anybody able to offer any assistance?
The Bit I've just added:
Worksheets("Sheet1").Columns("A:H").AutoFit
My Full Code:
Dim wb As Workbook, ws As Worksheet
Dim FileName As String, Path As String
Set wb = ActiveWorkbook
Set ws = ActiveSheet
Path = "C:\Users\Jonathan.mackell\Downloads\*.csv"
FileName = Dir(Path, vbNormal)
Do Until FileName = ""
Application.DisplayAlerts = False
Workbooks.Open Left(Path, Len(Path) - 5) & FileName
Worksheets("Sheet1").Columns("A:H").AutoFit
Set wb = ActiveWorkbook
For Each ws In wb.Worksheets
ws.PrintOut
Next
wb.Close
FileName = Dir()
Loop
End Sub
Any help appreciated!
set the wb variable when you open it instead of using activeworkbook, and include the sh variable instead of using activesheet, and put that in your loop, so you dont need to know the name.
Sub Test
Dim wb As Workbook, ws As Worksheet
Dim FileName As String, Path As String
Path = "C:\Users\Jonathan.mackell\Downloads\*.csv"
FileName = Dir(Path, vbNormal)
Do Until FileName = ""
Application.DisplayAlerts = False
Set wb = Workbooks.Open(Left(Path, Len(Path) - 5) & FileName)
For Each ws In wb.Worksheets
ws.Columns("A:H").AutoFit
ws.PrintOut
Next
wb.Close
FileName = Dir()
Loop
End Sub

Move specific tab from multiple workbooks into a single workbook

I have multiple workbooks which all have the tab named "example". I am wanting to adjust my current file to check if the current sheet is named "example", add the name of the workbook in front of "example" e.g. "File1 example" and move this tab into another file.
Currently i have the below, which pulls all tabs from all workbooks into a new workbook.
Sub GetSheets()
Path = "C:\TestPath\"
Filename = Dir(Path & "*.xls")
MsgBox (Filename)
Do While Filename <> ""
Workbooks.Open Filename:=Path & Filename, ReadOnly:=True
For Each Sheet In ActiveWorkbook.Sheets
Sheet.Copy After:=ThisWorkbook.Sheets(1)
Next Sheet
Workbooks(Filename).Close
Filename = Dir()
Loop
End Sub
Instead of looping through all sheets of a workbook you can just access it directly if you already know its name.
Also make sure not to exceed the max length that is allowed for a worksheet name. This is 31 characters so trim the workbook name or you might run into errors.
Public Sub GetSheets()
Dim Path As String
Path = "C:\TestPath\"
Dim Filename As String
Filename = Dir(Path & "*.xls")
Dim ws As Worksheet
MsgBox (Filename)
Dim OpenWb As Workbook
Do While Filename <> ""
Set OpenWb = Workbooks.Open(Filename:=Path & Filename, ReadOnly:=True)
OpenWb.Worksheets("example").Copy After:=ThisWorkbook.Sheets(ThisWorkbook.Sheets.Count) 'copy after last sheet
ThisWorkbook.Sheets(ThisWorkbook.Sheets.Count).Name = Left$(OpenWb.Name, 31) 'don't exceed max allowed length
OpenWb.Close False 'we do not save changes in the opened Workbook
Filename = Dir()
Loop
End Sub
Note an error handling might be needed if there is a possibility that any of the files has no worksheet named example.
Something like this should work for you.
Sub GetSheets()
Path = "C:\TestPath\"
Filename = Dir(Path & "*.xls")
Dim ws As Worksheet
MsgBox (Filename)
Do While Filename <> ""
Workbooks.Open Filename:=Path & Filename, ReadOnly:=True
For Each ws In ActiveWorkbook.Sheets
If ws.Name = "example" Then 'name of tab
ws.Name = ws.Name & " " & ActiveWorkbook.Name
ws.Copy After:=ThisWorkbook.Sheets(1)
Exit For
End If
Next ws
Workbooks(Filename).Close False 'we do not save changes in the opened Workbook
Filename = Dir()
Loop
End sub

Loop through excel files in a directory and copy onto master sheet

I have a folder with nearly 1000 .csv files. Each of these files contains 2 columns, and I would like to copy only one of these columns and transpose it onto a new workbook. The new workbook will contain all the data from each of these files. The following code is what I have generated:
Sub AllFiles()
Application.EnableCancelKey = xlDisabled
Dim folderPath As String
Dim Filename As String
Dim wb As Workbook
folderPath = "J:etc. etc. etc." 'contains folder path
If Right(folderPath, 1) <> "\" Then folderPath = folderPath + "\"
Filename = Dir(folderPath & "*.csv")
Do While Filename <> ""
Application.ScreenUpdating = False
Set wb = Workbooks.Open(folderPath & Filename)
wb.Range(Range("B1"), Range("B1").End(xlDown)).Select
Application.CutCopyMode = False
Selection.Copy
ActiveWorkbook.Close True
Windows("Compiled.xlsm").Activate
Worksheets("Sheet1").Range("A" & Rows.Count).End(xlUp).Offset(1, 0).PasteSpecial Transpose:=True
Filename = Dir
Loop
Application.ScreenUpdating = True
End Sub
For whatever reason the code does not work and a box pops-up saying "Code execution has been interrupted." Once I hit "Debug" the following line is highlighted:
wb.Range(Range("B1"), Range("B1").End(xlDown)).Select
I am not experienced with VBA at all and I am having trouble troubleshooting this issue. Any idea on what this means and what I can do?
The highlighted line is referring to a range on the workbook that is running the macro as opposed to the range within the workbook you have opened. Try replacing with this:
wb.Range(wb.Range("B1"), wb.Range("B1").End(xlDown)).Select
However I would suggest you avoid using the Select function altogether as it tends to slow down code. I've trimmed the loop a bit to avoid using Select and Activate:
Do While Filename <> ""
Application.ScreenUpdating = False
Set wb = Workbooks.Open(folderPath & Filename)
wb.Range(wb.Cells(1,"B"), wb.Cells(Rows.Count,"B").End(xlUp)).Copy
Workbooks("Compiled.xlsm").Worksheets("Sheet1").Range("A" & Rows.Count).End(xlUp).Offset(1, 0).PasteSpecial Transpose:=True
wb.Close True
Filename = Dir
Loop
Once you open file file, the active workbook is the book just opened and the active sheet is also established.
Your code fails primarily because of the wb.. (In general you would use a sheet reference instead), but in this case, replace:
wb.Range(Range("B1"), Range("B1").End(xlDown)).Select
with:
Range("B1").End(xlDown)).Select
(You also do not need Select to accomplish a copy/paste)
try with below
Sub AllFiles()
Application.EnableCancelKey = xlDisabled
Dim folderPath As String
Dim Filename As String
Dim wb As Workbook
folderPath = "c:\work\test\" 'contains folder path
If Right(folderPath, 1) <> "\" Then folderPath = folderPath + "\"
Filename = Dir(folderPath & "*.xlsx")
Do While Filename <> ""
Application.ScreenUpdating = False
Set wb = Workbooks.Open(folderPath & Filename)
Range("B1:B" & Range("B" & Rows.count).End(xlUp).Row).Copy
Workbooks("Compiled").Worksheets("Sheet1").Range("A" & Range("A" & Rows.count).End(xlUp).Row + 1).PasteSpecial Transpose:=True
Workbooks(Filename).Close True
Filename = Dir
Loop
Application.ScreenUpdating = True
End Sub
wb.Range(...) will never work since wb is a Workbook object. You need a Worksheet object. Try:
Dim ws As Worksheet
Set ws = wb.Activesheet
ws.Range(ws.Range("B1"), ws.Range("B1").End(xlDown)).Select

Excel Sheet Name Error

I'm using a VBA code to cycle through excel files in a directory and pull information from one worksheet and paste into a newly created worksheet. I'm also naming my new worksheets (in my destination file) by the name in one of the cells in the source file.
My code works for the first loop but fails/stops in the second loop (VBA points to an error in the Dest.Sheets.Add(After:=Dest.Sheets(Dest.Sheets.Count)).Name = Sheetname line. I need to loop through 75 of these files and I'm unsure of what's going on because it works correctly for the first file.
Thanks so much for the help!
Sub AddSummaryTables()
Dim Spath, Filename, Sheetname As String
Dim Source, Dest As Workbook
Dim WS As Worksheet
Set Dest = ThisWorkbook
Spath = InputBox("Enter File Source Path") & "\"
Filename = Dir(Spath & "*.xls*")
Do While Filename <> ""
Set Source = Workbooks.Open(Spath & Filename)
Sheetname = Source.Sheets("Summary").Range("B2").Text
MsgBox Sheetname
Dest.Sheets.Add(After:=Dest.Sheets(Dest.Sheets.Count)).Name = Sheetname
Source.Sheets("Summary").Range("A1:R150").Copy
Dest.Worksheets(Sheetname).Range("A1").PasteSpecial xlPasteValues
Dest.Worksheets(Sheetname).Range("A1").PasteSpecial xlPasteFormats
Dest.Worksheets(Sheetname).Range("A1:R150").WrapText = False
Dest.Worksheets(Sheetname).Rows.AutoFit
Dest.Worksheets(Sheetname).Columns.AutoFit
Source.Close SaveChanges:=False
Dest.Save
Filename = Dir()
Loop
End Sub
following Comintern's and Wyatt's suggestion you could try like follows
Option Explicit
Sub AddSummaryTables()
Dim sPath As String, fileName As String
Dim sourceWb As Workbook, destWb As Workbook
Dim sourceWs As Worksheet, destWs As Worksheet
Set destWb = ThisWorkbook
sPath = InputBox("Enter File Source Path") & "\"
fileName = Dir(sPath & "*.xls*")
Do While fileName <> ""
Set sourceWb = Workbooks.Open(sPath & fileName)
Set sourceWs = GetWorksheet(sourceWb, "Summary")
If Not sourceWs Is Nothing Then
Set destWs = SetWorksheet(destWb, sourceWs.Range("B2").Text)
sourceWs.Range("A1:R150").Copy
With destWs
.Range("A1").PasteSpecial xlPasteValues
.Range("A1").PasteSpecial xlPasteFormats
.UsedRange.WrapText = False
.Rows.AutoFit
.Columns.AutoFit
End With
sourceWb.Close SaveChanges:=False
destWb.Save
End If
fileName = Dir()
Loop
End Sub
Function GetWorksheet(wb As Workbook, sheetName As String) As Worksheet
On Error Resume Next
Set GetWorksheet = wb.Worksheets(sheetName)
On Error GoTo 0
End Function
Function SetWorksheet(wb As Workbook, sheetName As String) As Worksheet
Dim i As Integer
Do While Not GetWorksheet(wb, sheetName & IIf(i = 0, "", "-" & i)) Is Nothing
i = i + 1
Loop
With wb
.Worksheets.Add(After:=.Worksheets(.Worksheets.Count)).Name = sheetName & IIf(i = 0, "", "-" & Format(i, "000"))
Set SetWorksheet = .ActiveSheet
End With
End Function
where you make sure that
any opened workbook has a "Summary" worksheet
you name worksheets in your destination workbook such as not to have duplicates: if you happen to deal with say three worksheets named "Sheet5" then your destination workbook will have added worksheets "Sheet5", "Sheet5-001" and "Sheet5-002".
You're issue may be that when you are adding the sheet from the second workbook, it has the same name as the sheet from the first workbook. You could check if the sheet exists and add a number to it. The post below might help.
Test or check if sheet exists

PasteSpecial Method of Range Run Error

Sub LoopOtherRevenue()
Dim MyFile As String
Dim FilePath As String
FilePath = "C:\Users\jdubbaneh002\Desktop\Racetrac Other\"
MyFile = Dir(FilePath)
Do While Len(MyFile) > 0
If MyFile = "Book1.xlsm" Then
Exit Sub
End If
ActiveSheet.Range("A1:B14").Copy
Workbooks.Open (FilePath & MyFile)
ActiveWorkbook.Worksheets("A2) Monthly P&L (Source)").Activate
Range("B746:C759").PasteSpecial xlPasteValues
Application.CutCopyMode = False
ActiveWorkbook.Close
MyFile = Dir
Loop
End Sub
Get a paste special error on line Range("B746:C759").PasteSpecial xlPasteValues
The values are being pasted into a combo box. that is where the error is coming from.
For me it seems like the file path is missing a "\"
FilePath = "C:\Users\jdubbaneh002\Desktop\Racetrac Other"
...
MyFile = Dir(FilePath)
...
If MyFile = "Book1.xlsm" Then
...
Workbooks.Open (FilePath & MyFile)
Correct:
Workbooks.Open (FilePath & "\" & MyFile)
Did you try debugging? Where does it throw the error?
I can see all sorts of issues because you're using ActiveWorkbook after opening the 2nd workbook. Is ActiveWorkbook still pointing at the one where the code is, or is it actually pointing at the one you just opened?
Create & set an as Workbook variable as assign the one the code is in to one, and the workbook you're opening to the other. That will eliminate all confusion.
Try this:
Sub LoopOtherRevenue()
Dim rgCopy as Range
Dim MyFile As String
Dim FilePath As String
Dim wb as Workbook
FilePath = "destination folder\"
MyFile = Dir(FilePath)
Set rgCopy = ActiveSheet.Range("A1:B14")
Do While Len(MyFile) > 0
If MyFile = "Book1.xlsm" Then
Exit Sub
End If
set wb Workbooks.Open(FilePath & "\" & MyFile)
rgCopy.Copy Destination:=wb.Worksheets("A2) Monthly P&L (Source)").Range("B746")
wb.Close
MyFile = Dir
Loop
End Sub