Loop to unfilter multiple excel workbooks VBA - vba

I am trying to do a loop to unfilter the column A for all the workbooks (as they are the same, alwyas column A).
I want to show all the cells as the filter romve the empty cells.
I have many of folders ( more than 50) so the loop is very useful and important for the next step of my code.
I have a code that works for one folder:
`Sub unfilterr()
Dim y As Workbook, myfile, FolderPath, path
Dim ws As Excel.Worksheet
Set y = Workbooks.Open("Z:\VBA\Copie de Devis_65 Version
avec G35.xlsx")
With y.Worksheets("Para RF")
If Not y.Worksheets("Para RF").AutoFilter Is Nothing Then
y.Sheets("Para RF").Range("A1").AutoFilter Field:=1
End If
End With
End Sub`
and now trying to do the loop:
`Sub unfilter1()
Dim y As Workbook, myfile, FolderPath, path
Dim ws As Excel.Worksheet
'## Open workbooks first:
Application.ScreenUpdating = False
Application.EnableEvents = False
Application.Calculation = xlCalculationManual
FolderPath = "Z:\VBA\Test\"
path = FolderPath & "*.xls*"
myfile = Dir(FolderPath & "*.xls*")
Do While myfile <> ""
Set y = Workbooks.Open(path) 'I put path instead of myfile because I have error if I put myfile
Set ws = y.Worksheets("Para RF")
'With ws
If Not ws.AutoFilter Is Nothing Then
y.Sheets("Para RF").Range("A1").AutoFilter Field:=1
End If
'End With
myfile = Dir()
y.Close saveChanges:=True
Loop
MsgBox ("Task Complete")
End Sub
can you please tell what is the problem with this loop!?
I am trying it on 4 workbooks in the test folder! only the first one is unfiltered while the others are not. It seems like the loop is repeting on only the first workbook in the folder.
So with this loop no error message but the result is unsatisfing.
Thank you a lot for your help.
cheers!

The Workbook.Open() method needs a full path and the filename.
Replace
Set y = Workbooks.Open(path)
With
Set y = Workbooks.Open(FolderPath & myfile)
and you should be good to go.
You don't need the path variable.
Edit: I minimized your whole script to the bare minimum to loop through all ".xls" files and open all off them within a folder:
Sub OpenWorkbooks()
Dim y As Workbook
Dim myfile As String
Dim FolderPath As String
FolderPath = "C:\TestDirectory\"
myfile = Dir(FolderPath & "*.xls*")
Do While myfile <> ""
Set y = Workbooks.Open(FolderPath & myfile)
myfile = Dir()
Loop
End Sub
The above opens each Excel file in C:\TestDirectory\ on my machine.
N.b. make sure you have the "\" at the end of the FolderPath variable, otherwise it'll look for C:\TestDirectorySomeFileName.xlsx which is not going to work.

Related

excel VBA 1004 error when copying multiple tabs into one tab from a folder

I am getting a 1004 error when I try and combine workbook pages into one master document. The code works correctly on my device, but when I attempt to run the code on my friends device it throw a 1004 error. I believe he is on excel 2013, I am on excel 2016. Is there any way to convert my code into something that can be used on both devices?
Sub CombineSheets()
Dim sPath As String
Dim sFname As String
Dim wBk As Workbook
Dim wSht As Variant
Application.EnableEvents = False
Application.ScreenUpdating = False
sPath = InputBox("Enter a full path to workbooks")
ChDir sPath
sFname = InputBox("Enter a filename pattern")
sFname = Dir(sPath & "\" & sFname & ".xl*", vbNormal)
wSht = InputBox("Enter a worksheet name to copy")
Do Until sFname = ""
Set wBk = Workbooks.Open(sFname)
Windows(sFname).Activate
Sheets(wSht).Copy Before:=ThisWorkbook.Sheets(1)
wBk.Close False
sFname = Dir()
Loop
ActiveWorkbook.Save
Application.EnableEvents = True
Application.ScreenUpdating = True
End Sub
This works correctly when I run it, prompts for the folder location, asks which files it should copy from (usually *), and then copies from specifically the worksheet name entered.
Realistically all I need is code that can extract one worksheet from several hundred excel files and combine them into one master document. being able to pick and choose which worksheets would just be a bonus.
Thank you!
Like Mat's Mug said, you should really validate you inputs.
Did your co-worker add a "\" at the end of the path? Does the Path even exist?
Test to make sure that the sheet exists in the file that you are copying from, with something like this:
Function SheetExists(Name As String, Optional Workbook As Excel.Workbook = Nothing) As Boolean
If Workbook Is Nothing Then Set Workbook = ThisWorkbook.Application.ActiveWorkbook
On Error Resume Next
If Workbook.Worksheets(Name).Name <> vbNullString Then
End If
If Err.Number = 0 Then SheetExists = True
On Error GoTo 0
End Function
Here is your code with the noted changes:
Sub CombineSheets()
Dim sPath As String
Dim sFname As String
Dim wBk As Workbook
Dim sSht As String
Application.EnableEvents = False
Application.ScreenUpdating = False
sPath = InputBox("Enter a full path to workbooks")
'Use the FolderPicker to verify the path
With Application.FileDialog(msoFileDialogFolderPicker)
If .Show Then sPath = .SelectedItems(1)
End With
'ChDir sPath
sFname = InputBox("Enter a filename pattern")
sFname = Dir(sPath & "\" & sFname & ".xl*", vbNormal)
sSht = InputBox("Enter a worksheet name to copy")
Do Until sFname = ""
Set wBk = Workbooks.Open(sFname)
'Windows(sFname).Activate
If SheetExists(sSht, wBk) Then
wBk.Sheets(sSht).Copy Before:=ThisWorkbook.Sheets(1)
End If
wBk.Close False
sFname = Dir()
Loop
'ActiveWorkbook.Save
ThisWorkbook.Save
Application.EnableEvents = True
Application.ScreenUpdating = True
End Sub
The bigger question is, are the Sheets the same size? Old .xls files only have 65536 rows, where 2007+ .xlsx files go up to 1048576 rows.
You can't mix the two different worksheets. In that case, you need to copy all of the cells from one sheet to the other.
wBk.Sheets(sSht).Cells.Copy
ThisWorkbook.Sheets.Add Before:=ThisWorkbook.Sheets(1)
ThisWorkbook.Sheets(1).Paste

VBA Change code from MSG Box to Summary Report

Good afternoon,
I have tried searching different forums to no avail.
I have the below VBA code that will loop through all files in a folder and generate in a msge box the total number of rows of every file looped in that folder.
What I need your help on if possible is generate a summary report.
Ideally
The summary report will show File name and show how many rows with data in column H.
Sub LoopThroughFiles()
Dim folderPath As String
folderPath = ThisWorkbook.Path & "\"
Filename = Dir(folderPath & "*.xlsx")
Do While Filename <> ""
Set wb = Workbooks.Open(folderPath & Filename, ReadOnly:=True)
For Each sh In wb.Sheets
If Application.CountA(sh.Range("H:H")) > 0 Then
myCount = myCount + sh.Range("H" & Rows.Count).End(xlUp).Row
End If
Next
wb.Close False
Filename = Dir
Set wb = Nothing
Loop
MsgBox myCount
End Sub
You could try opening a "home" workbook where all values are stored. Basically, what you'll need to do is open a new workbook, and during your loop through each of the files, you'll paste the file path and the row count in the new workbook. Hopefully this will help, or at least give you an idea of how to do what you're trying to do. `
Sub LoopThroughFiles()
Dim folderPath As String
Dim summarySheet as Workbook
set summarySheet = workbook.add
folderPath = ThisWorkbook.Path & "\"
Filename = Dir(folderPath & "*.xlsx")
Do While Filename <> ""
Set wb = Workbooks.Open(folderPath & Filename, ReadOnly:=True)
For Each sh In wb.Sheets
If Application.CountA(sh.Range("H:H")) > 0 Then
myCount = myCount + sh.Range("H" & Rows.Count).End(xlUp).Row
End If
Next
wb.Close False
summarySheet.activate
Range("A:A").insert Shift:=xlDown
Cells(1,1) = Filename
Cells(1,2) = myCount
Filename = Dir
Set wb = Nothing
Loop
MsgBox myCount
End Sub`

Do While loop not looping nor doing

In a quest to further never do anythign manual ever again
I made an it.xlsm that you have to put together in a folder with a specific file that has to be processed.
This it.xslm has three modules:
Masterfile
- renames the categories in C
-makes a worksheet per category in C
-saves those worksheets as .xslx. This results in 8 new files in a /Departement folder
Littlefiles
-renames the categories in E
-makes tabs for each category
-cleans up empty columns.
placeholder
Opens the .xls with the data
Applies Masterfile
Opens all the files created by masterfiles
makes tabs and cleans up empty columns.
Placeholder's code:
Sub OpenBigFile()
Dim wb As Workbook
Dim ws As Worksheet
Dim Lastrow As Long
'open main file, apply masterfile moduke
Set wb = Workbooks.Open(ThisWorkbook.path & "\Depositformulier (Reacties).xlsx")
Call masterfile.total
wb.Close SaveChanges:=True
End Sub
This works fine.
Sub OpenAllFiles()
Dim wb As Workbook
Dim myPath As String
Dim myFile As String
myPath = ThisWorkbook.path & "\" & "Departement" & "\"
myFile = Dir(myPath & "*.xlsx")
Do While Len(Filename) > 0
DoEvents
Set wb = Workbooks.Open(myPath & myFile, True, True)
Call LittleFiles.total
wb.Close False
myFile = Dir
Loop
End Sub
Here I find myself in problems. I tried to rewrite it many times, using many examples, but always it seems to be stuck at Set wb = Workbooks.Open(Filename:=myPath & myFile)
What am I doing wrong?
Do you need my Littlefiles code?
Also, in general, is it correct that 'ThisWorkbook' will always refer to the this.xlm,even if in the mean time another workbook is active (this being ActiveWorkbook)?
Thanks a bunch
Here's my attempt, i think this way it'll be harder to go wrong as you will have the full path of the file already stored:
Sub OpenAllFiles()
'create an array
Dim myFiles As Variant
ReDim myFiles(500)
myPath = ThisWorkbook.Path
If Right(myPath, 1) <> "\" Then
myPath = myPath & "\"
End If
'search for at least 5 files in the folder specified above, add the entire path to the array
While myCount < 5
If Dir(myPath & "*.xlsm") <> "" Then
potentialFileToLoad = Dir(myPath & "*.xlsm")
While potentialFileToLoad <> ""
myFiles(myCount) = myPath & potentialFileToLoad
myCount = myCount + 1
potentialFileToLoad = Dir
Wend
End If
Wend
'change size of array to ammount of files found
ReDim Preserve myFiles(myCount - 1)
For Each ii In myFiles
'(Insert Open, Run code, close code here)
Workbooks.Open (ii), True, True
Call LittleFiles.Total
ActiveWorkbook.Close
Next ii
End Sub
try something similar to this
path = "path2folder" & "\" 'this is fairly important and probably why your code breaks?_
you cant add the backslash like you do above
Filename = Dir(path & "*.xl??")
Do While Len(Filename) > 0
DoEvents
Set wbk = Workbooks.Open(path & Filename, True, True)
'add your code
wbk.Close False
Filename = Dir
Loop

Create macro to output and update file after merging several excel files

I am a novice at VBA. I am using Excel 2013 for this task. I have several Excel files I am combining into a single file with multiple sheets using the macro below.
Sub Merge2MultiSheets()
Dim wbDst As Workbook
Dim wbSrc As Workbook
Dim wsSrc As Worksheet
Dim MyPath As String
Dim strFilename As String
Application.DisplayAlerts = False
Application.EnableEvents = False
Application.ScreenUpdating = False
MyPath = "H:\Survey Research\ECAS\Reports\2015\Tracks"
Set wbDst = Workbooks.Add(xlWBATWorksheet)
strFilename = Dir(MyPath & "\*.xls", vbNormal)
If Len(strFilename) = 0 Then Exit Sub
Do Until strFilename = ""
Set wbSrc = Workbooks.Open(FileName:=MyPath & "\" & strFilename)
Set wsSrc = wbSrc.Worksheets(1)
wsSrc.Copy After:=wbDst.Worksheets(wbDst.Worksheets.Count)
wbSrc.Close False
strFilename = Dir()
Loop
wbDst.Worksheets(1).Delete
Application.DisplayAlerts = True
Application.EnableEvents = True
Application.ScreenUpdating = True
End Sub
I want each sheet in the new file to take the name of its original file. I tried to edit the code below and include in the macro above, but while I didn't get an error message, it did not accomplish the task.
Do While fileName <> ""
Workbooks.Open (directory & fileName)
WrdArray() = Split(fileName, ".")
For Each sheet In Workbooks(fileName).Worksheets
Workbooks(fileName).ActiveSheet.Name = WrdArray(0)
total = Workbooks("import-sheets.xlsm").Worksheets.Count
Workbooks(fileName).Worksheets(sheet.Name).Copy after:=Workbooks("import- sheets.xlsm").Worksheets(total)
Once the files have been merged and the sheets named, I want to output the new file and to easily update it if the data in my original files change.
Is it possible to achieve all of this with one macro? If so, could anyone suggest a way to write a Macro in Excel to automatically name the sheets, output the file and update it if changes are made to the data in the original files?
For the first part I think you only need to add one line:
Do Until strFilename = ""
Set wbSrc = Workbooks.Open(FileName:=MyPath & "\" & strFilename)
Set wsSrc = wbSrc.Worksheets(1)
'name the tab according to the file name
wsSrc.Name = Replace(strFilename,".xls","")
wsSrc.Copy After:=wbDst.Worksheets(wbDst.Worksheets.Count)
wbSrc.Close False
strFilename = Dir()
Loop
The last part about updating the workbook if the source files change is potentially much more complex: the easiest approach would be to re-run the consolidation code. If that doesn't work for you then you'd need to add more details on that.

Excel VBA : Looping a simple copy of a worksheet over multiple workbooks in a folder

I'm attempting to apply a macro that would copy and paste one specific worksheet (call the title of that worksheet "x") from one workBOOK ("x1") , onto a master workBOOK (call that workBOOK "xmaster"), after it copy and pastes the worksheet from workbook x1 it should also rename the title of the worksheet "x" to cell B3. This should be done before it moves to the next workbook.
It would need to do this for workBOOK x1 through, say, x100. I cannot refer to the workbook by name though, because they are each named a string of text that is in no real sortable method.
This code I know works, copying "x" from "x1" to "xmaster", along with renaming the sheet, and breaking the links, is the following:
Sub CombineCapExFiles()
Sheets("Capital-Projects over 3K").Move After:=Workbooks("CapEx Master File.xlsm").Sheets _
(3)
ActiveSheet.Name = Range("B3").Value
Application.DisplayAlerts = False
For Each wb In Application.Workbooks
Select Case wb.Name
Case ThisWorkbook.Name, "CapEx Master File.xlsm"
' do nothing
Case Else
wb.Close
End Select
Next wb
Application.DisplayAlerts = True
End Sub
The Activate Previous window isn't working, also not sure how to fix that portion of it.
I'm not sure how to build this to loop through all workBOOKs in the directory, however.
Should I use this:?
MyPath = "C:\directory here"
strFilename = Dir(MyPath & "\*.xlsx", vbNormal) 'change to xlsm if needed ?
If Len(strFilename) = 0 Then Exit Sub ' exit if no files in folder
Do Until strFilename = ""
'Your code here
strFilename = Dir()
Loop
An additional constraint is that it needs to not run the macro on xmaster (it will have an error because it will not have the sheet "x" which will be renamed from the previous workbooks.)
Thanks!
Matthew
like this?
(not tested)
Option Explicit
Sub LoopFiles()
Dim strDir As String, strFileName As String
Dim wbCopyBook As Workbook
Dim wbNewBook As Workbook
Dim wbname as String
strDir = "C:\"
strFileName = Dir(strDir & "*.xlsx")
Set wbNewBook = Workbooks.Add 'instead of adding a workbook, set = to the name of your master workbook
wbname = ThisWorkbook.FullName
Do While strFileName <> ""
Set wbCopyBook = Workbooks.Open(strDir & strFileName)
If wbCopyBook.FullName <> wbname Then
wbCopyBook.Sheets(1).Copy Before:=wbNewBook.Sheets(1)
wbCopyBook.Close False
strFileName = Dir()
Else
strFileName = Dir()
End If
Loop
End Sub
This bit will work to avoid running the macro on xmaster.
xmaster = "filename for xmaster"
MyPath = "C:\directory here"
strFilename = Dir(MyPath & "\*.xls*", vbNormal) 'this will get .xls, .xlsx, .xlsm and .xlsb files
If Len(strFilename) = 0 Then Exit Sub ' exit if no files in folder
Do Until strFilename = ""
If strFileName = xmaster Then ' skip the xmaster file
strFilename = Dir()
End If
'Your code here
strFilename = Dir()
Loop
I can't help on the other part though. I don't see any Activate Previous window part in your code.