Looping through file extensions, excel vba - excel

I am using an Array of File extensions and looping through a folder of workbooks. The code is naming Sheet(1).name="MyName"
I notice that even though "*.xlsm" is not in the array, it is still opening and naming the sheet.
Here's the code. Can anybody see if they get the same problem and are able to solve it.
Sub LoopThroughFolder()
Dim MyFile As String, Str As String, MyDir As String, Wb As Workbook
Dim Rws As Long, Rng As Range
Dim fExt, ext
Set Wb = ThisWorkbook
'change the address to suite
MyDir = "C:\TestWorkBookLoop\"
ChDir MyDir
Application.ScreenUpdating = 0
Application.DisplayAlerts = 0
fExt = Array("*.xlsx", "*.xls") 'file extensions, set the file extensions of the files to move
For Each ext In fExt 'loop through file extensions
MyFile = Dir(MyDir & ext)
Do While MyFile <> ""
Workbooks.Open (MyFile)
Sheets(1).Name = "MySheet"
With ActiveWorkbook
.Save
.Close
End With
MyFile = Dir()
Loop
Next ext
End Sub

The legacy short (8.3) file name for HELLO.ABCD would look something like ABCDEF~1.ABC - see the extension is truncated to 3 characters.
In your case GET.XLSM would be ABCDEF~1.XLS and this 8.3 form is also matched by the Win32 API FindFirstFile (which is what Dir() calls under the hood) when you specify *.XLS
Just filter out the exceptions in you loop with
If Not UCase$(MyFile) Like "*.XLSM" Then
....

While Alex has solved your query, I have updated your code below to
ensure it handles all excel file types
handle the sheet name already existing (else your code will error out)
cleanup and properly use variables
restore events at close
Sub LoopThroughFolder()
Dim Wb As Workbook
Dim MyFile As String
Dim MyDir As String
Dim StrFile As String
MyDir = "C:\temp\"
ChDir MyDir
With Application
.ScreenUpdating = False
.DisplayAlerts = False
End With
StrFile = "*.xls*"
MyFile = Dir(MyDir & StrFile)
Do While Len(MyFile) > 0
If MyFile Like "*.xlsx" Or MyFile Like "*.xlx" Then
Set Wb = Workbooks.Open(MyFile)
On Error Resume Next
Wb.Sheets(1).Name = "MySheet"
On Error GoTo 0
Wb.Save
Wb.Close False
End If
MyFile = Dir()
Loop
With Application
.ScreenUpdating = True
.DisplayAlerts = True
End With
End Sub

Related

Excel VBA - Multiple Dir() in Same Folder

I am working on this codes, but can't make it work.
Here is my working code:
Sub AREA21()
Dim wb As Workbook
Dim myPath As String
Dim myFile As String
Dim regFile As String
Dim myExtension As String
Dim RegX As String
'Optimize Macro Speed
Application.ScreenUpdating = False
Application.EnableEvents = False
Application.Calculation = xlCalculationManual
ThisWorkbook.UpdateLinks = xlUpdateLinksNever
myPath = "C:\Users\Aspire E 14\Desktop\xx\xxx\"
'In Case of Cancel
NextCode:
myPath = myPath
If myPath = "" Then GoTo ResetSettings
'Target File Extension (must include wildcard "*")
myExtension = "*area trees yield of NFICCs in *.xls*"
RegX = "*area trees yield of NFICCs in REG*.xls*"
'Target Path with Ending Extention
myFile = Dir(myPath & myExtension)
regFile = Dir(RegX & myExtension)
'Loop through each Excel file in folder
Do While myFile <> ""
'Set variable equal to opened workbook
If myFile = regFile Then GoTo skipRegFile
Set wb = Workbooks.Open(Filename:=myPath & myFile, UpdateLinks:=False)
'Ensure Workbook has opened before moving on to next line of code
DoEvents
'my codes here
For i = 1 To Sheets.Count
Sheets(i).Select
Next i
'Save and Close Workbook
wb.Close SaveChanges:=True
'Ensure Workbook has closed before moving on to next line of code
DoEvents
skipRegFile:
'Get next file name
myFile = Dir
Loop
'Message Box when tasks are completed
MsgBox "Task Complete!"
ResetSettings:
'Reset Macro Optimization Settings
Application.ScreenUpdating = True
Application.EnableEvents = True
Application.Calculation = xlCalculationAutomatic
ThisWorkbook.UpdateLinks = xlUpdateLinksAlways
End Sub
Here is the sample folder:
Files with "REG**" are just the summary of respective provinces.
My goal is to run the codes in provincial files, and skip opening the file if it is a regional summary. However, problems occur when getting the next file in Dir statement as it appears blank.
Still looking for a better work around.
You can adapt this code to suit your needs.
Some suggestions:
Name your variables to something meaningful (sh is hard to understand, sourceRange it's easier)
Indent your code properly (you can use Rubberduckvba.com) to help you with data
Try to break your code into pieces (e.g. first validate, then prepare, then add items)
Comment your code
Code:
Public Sub Area21()
' Basic error handling
On Error GoTo CleanFail
' Turn off stuff
Application.ScreenUpdating = False
Application.EnableEvents = False
Application.Calculation = xlCalculationManual
ThisWorkbook.UpdateLinks = xlUpdateLinksNever
' Define files path
Dim filesPath As String
filesPath = "C:\TEMP\"
' Define file name string to match
Dim fileString As String
fileString = "demo"
' Define file name
Dim fileName As String
fileName = Dir(filesPath, vbNormal)
' Loop through files
Do While fileName <> ""
'Set variable equal to opened workbook
If InStr(LCase(fileName), LCase(fileString)) > 0 Then
' Set a reference to the workbook
Dim targetWorkbook As Workbook
Set targetWorkbook = Workbooks.Open(fileName:=filesPath & fileName, UpdateLinks:=False)
'Ensure Workbook has opened before moving on to next line of code
DoEvents
' DO SOMETHING WITH THE WORKBOOK
'Save and Close Workbook
targetWorkbook.Close SaveChanges:=True
'Ensure Workbook has closed before moving on to next line of code
DoEvents
End If
fileName = Dir()
Loop
CleanExit:
' Turn on stuff
Application.ScreenUpdating = True
Application.EnableEvents = True
Application.Calculation = xlCalculationAutomatic
ThisWorkbook.UpdateLinks = xlUpdateLinksAlways
Exit Sub
CleanFail:
MsgBox "Error " & Err.Description
GoTo CleanExit
End Sub

why is my wildcard character not registering through the directory?

I have a subfolder looping script that identifies if Cells(2,3) is blank, and then proceeds to delete the column, if so.
I have a wildcard character * in order to not have to name any of the files, just extensions. Why is this line: MyFile = "*.xlsx" not picking up the actual file names? It's just displaying as *.xlsx within the loop and exiting the sub because nothing is found.
Edited Code based on Answer:
Sub LoopSubfoldersAndFiles()
Dim folder As Object
Dim subfolders As Object
Dim MyFile As String
Dim wb As Workbook
Dim currentfile As Object, currentfolder As Object
With Application
.ScreenUpdating = False
.EnableEvents = False
.Calculation = xlCalculationManual
End With
Set subfolders = folder.subfolders
MyFile = "*.xlsx"
For Each subfolders In subfolders
Set CurrentFile = subfolders.Files
With New FileSystemObject ' reference Microsoft Scripting Runtime library
Dim root As folder
Set root = .GetFolder("C:\Users\pp87255\Desktop\JNav Rest\05.23.2019")
Dim subFolder As folder
For Each subFolder In root.subfolders
Dim currentfolder As folder
For Each currentfolder In subFolder.subfolders
Dim currentfile As File
For Each currentfile In currentfolder.Files
If currentfile.Name Like "*.xlsx" Then
Dim wb As Workbook
Set wb = Application.Workbooks.Open(currentfile.Path)
If wb.Sheets(1).Cells(2, 3).Value2 = "" Then
Columns(3).EntireColumn.Delete
End If
End If
Next
Next
Next
End With
Next
Set folder = Nothing
Set subfolders = Nothing
With Application
.EnableEvents = True
.Calculation = xlCalculationAutomatic
.ScreenUpdating = True
End With
End Sub
If CurrFile.Name = MyFile Then
With MyFile being "*.xlsx", the = comparison operator is correctly saying "nope, doesn't match".
What you want is to replace that operator with the Like operator, with the caveat that you'll need a literal expression on the right-hand side:
If CurrFile.Name Like "*.xlsx" Then
That should work as intended... until this part:
Workbooks.Open(subfolders.Path & "\" & MyFile)
You probably mean to use CurrFile there (Workbooks.Open isn't expecting a wildcard in the filename there)... but this is weird and ambiguous:
For Each CurrFile In CurrFile
Don't do that. Declare a new variable instead or repurposing an existing one in the same scope. Same here:
For Each subfolders In subfolders
You want For Each subFolder In subFolders, then For Each currFile In currFiles, maybe - or better:
With New FileSystemObject ' reference Microsoft Scripting Runtime library
Dim root As Folder
Set root = .GetFolder("C:\Users\pp87255\Desktop\JNav Rest\05.23.2019")
Dim subFolder As Folder
For Each subFolder In root.SubFolders
Dim currentFolder As Folder
For Each currentFolder In subFolder.SubFolders
Dim currentFile As File
For Each currentFile In currentFolder.Files
If currentFile.Name Like "*.xlsx" Then
Dim wb As Workbook
Set wb = Application.Workbooks.Open(currentFile.Path)
'...
End If
Next
Next
Next
End With
Working late-bound is hard if you're not familiar with the libraries involved. The good news is, there's no reason whatsoever to late-bind the Scripting library (it's the same version on every Windows box ever built this century) - so go to Tools > Rerefences, and check the "Microsoft Scripting Runtime" library.
I repurposed this code from "www.thespreadsheetguru.com". It loops through all files in the folder I navigate to, and formats them.
Private Sub FormatAllFilesInFolder()
'PURPOSE: To loop through all Excel files in a user specified folder and perform a set task on them
'SOURCE: www.TheSpreadsheetGuru.com
Dim WB As Workbook
Dim myPath As String
Dim MyFile As String
Dim myFileName As String
Dim myExtension As String
Dim FldrPicker As FileDialog
Dim regionNumber As String
'Optimize Macro Speed
Application.ScreenUpdating = False
Application.EnableEvents = False
Application.Calculation = xlCalculationManual
'Retrieve Target Folder Path From User
Set FldrPicker = Application.FileDialog(msoFileDialogFolderPicker)
With FldrPicker
.Title = "SELECT THE FOLDER WITH REPORT COLLECTION WORKBOOKS TO BE FORMATTED"
.AllowMultiSelect = False
If .Show <> -1 Then GoTo NextCode
myPath = .SelectedItems(1) & "\"
End With
'In Case of Cancel
NextCode:
myPath = myPath
If myPath = "" Then GoTo ResetSettings
'Target File Extension (must include wildcard "*")
myExtension = ".xlsx"
'Target Path with Ending Extention
MyFile = Dir(myPath)
'branchLocation = fso.GetBaseName(Right(myFile, Len(myFile) - InStr(myFile, "_")))
GetSaveFileLocation
'Loop through each Excel file in folder
Do While MyFile <> ""
Application.DisplayAlerts = False
myFileName = fso.GetBaseName(MyFile)
'Set variable equal to opened workbook
Set WB = Workbooks.Open(fileName:=myPath & MyFile)
fName = myFileName & "_Formatted"
saveFileName = mySavePath & fName & myExtension
If WB.Application.ProtectedViewWindows.Count > 0 Then
WB.Application.ActiveProtectedViewWindow.Edit
End If
ExecutiveReportFormatting
regionNumber = getRegionNumber(myFileName)
WB.BuiltinDocumentProperties("Comments").Value = regionNumber
'Close Workbook
With WB
.SaveAs saveFileName
.Close
End With
'Get next file name
MyFile = Dir
Loop
ResetSettings:
'Reset Macro Optimization Settings
Application.EnableEvents = True
Application.Calculation = xlCalculationAutomatic
Application.DisplayAlerts = True
End Sub

Open Multiple Excel Files and Add New Cells

I'm trying to open multiple Excel files and add the same new cell with same name to each. They are in a folder .../desktop/excel named workbook1, workbook2, etc.
I tried this article already but I'm getting a runtime error 76 'Path not found'.
I'm super novice with VBA, any help is appreciated! This is the script I'm running:
Sub LoopThroughFolder()
Dim MyFile As String, Str As String, MyDir As String, Wb As Workbook
Dim Rws As Long, Rng As Range
Set Wb = ThisWorkbook
'change the address to suite
MyDir = "C:\Users\shaye\Desktop\excel" 'Your Directory
MyFile = Dir(MyDir & "*.xlsx") 'Your excel file extension
ChDir MyDir
Application.ScreenUpdating = 0
Application.DisplayAlerts = 0
Do While MyFile <> ""
Workbooks.Open (MyFile)
Range("G1").Value = "NewColumn" 'New Column Name
ActiveWorkbook.Save
ActiveWorkbook.Close True
MyFile = Dir()
Loop
End Sub
[
try this code. I think you need this "\" in your directory and "??" in your file extension to find several excel types
Sub LoopThroughFolder()
Dim MyFile As String, Str As String, MyDir As String, Wb As Workbook
Dim Rws As Long, Rng As Range
Set Wb = ThisWorkbook
'change the address to suite
MyDir = "C:\Users\shaye\Desktop\excel\" 'Your Directory need this "\"
MyFile = Dir(MyDir & "*.xl??") 'Your excel file extension
Application.ScreenUpdating = 0
Application.DisplayAlerts = 0
Do While MyFile <> ""
Workbooks.Open (MyFile)
Range("G1").Value = "NewColumn" 'New Column Name
ActiveWorkbook.Save
ActiveWorkbook.Close True
MyFile = Dir()
Loop
End Sub

Converting XLS/XLSX files in a folder to CSV

I have written the following code in VBA. When debugging, I am not able to find any problems. It is not creating nor converting any file into .CSV.
Sub SaveToCSVs()
Dim fDir As String
Dim Wb As Workbook
Dim wS As Worksheet
Dim csvWs As String, csvWb As String
Dim extFlag As Long '0 = .xls & 1 = .xlsx extension types
Dim fPath As String
Dim sPath As String, dd() As String
fPath = "C:\Users\DA00358662\Documents\XLSCONV\*.*"
sPath = "C:\Users\DA00358662\Documents\XLSCONV\"
fDir = Dir(fPath)
extFlag = 2
Do While (fDir <> "")
If Right(fDir, 4) = ".xls" Or Right(fDir, 5) = ".xlsx" Then
extFlag = 0
Else
extFlag = 2
End If
On Error Resume Next
If extFlag = 0 Then
fDir = Dir
Set Wb = Workbooks.Open(fPath & fDir)
csvWb = Wb.Name
dd = Split(csvWb, ".")
For Each wS In Wb.Sheets
wS.SaveAs dd(0) & wS.Name & ".csv", xlCSV
Next wS
Wb.Close False
Set Wb = Nothing
fDir = Dir
On Error GoTo 0
End If
Loop
End Sub
with this code (standard for my use) you can find that you need (modify as your need).
In short the code ask which directory to loop and for each file, with the corresponding extension, in this directory it open file, save as csv in the some directory, and close the original file.
Sub SaveAsCsv()
Dim wb As Workbook
Dim sh As Worksheet
Dim myPath As String
Dim myFile As String
Dim myExtension As String
Dim FldrPicker As FileDialog
'Optimize Macro Speed
Application.ScreenUpdating = False
Application.EnableEvents = False
Application.Calculation = xlCalculationManual
'Retrieve Target Folder Path From User
Set FldrPicker = Application.FileDialog(msoFileDialogFolderPicker)
With FldrPicker
.Title = "Select A Target Folder"
.AllowMultiSelect = False
If .Show <> -1 Then GoTo NextCode
myPath = .SelectedItems(1) & "\"
End With
'In Case of Cancel
NextCode:
myPath = myPath
If myPath = "" Then Exit Sub
'Target File Extension (must include wildcard "*")
myExtension = "*.xls*"
'Target Path with Ending Extention
myFile = Dir(myPath & myExtension)
'Loop through each Excel file in folder
Do While myFile <> ""
'Set variable equal to opened workbook
Set wb = Workbooks.Open(Filename:=myPath & myFile)
nameWb = myPath & Left(myFile, InStr(1, myFile, ".") - 1) & ".csv"
ActiveWorkbook.SaveAs Filename:=nameWb, FileFormat:=xlCSV
ActiveWorkbook.Close savechanges:=False
'Get next file name
myFile = Dir
Loop
'Reset Macro Optimization Settings
Application.ScreenUpdating = True
Application.EnableEvents = True
Application.Calculation = xlCalculationAutomatic
End Sub
The Moment you concatenate fPath and fDir to open your Workbook, you get something like:
"C:\Users\DA00358662\Documents\XLSCONV\*.*MyWorkbook.xls"
Note *.* in the middle ruining your day. I think you want to use sPath here?

Batch convert Excel to text-delimited files

Hi I'm facing a problem on dealing with converting Excel spreadsheets to txt files.
What I want to do is to create a Macro which can takes all the xls files in one folder and convert them to txt files.
The code currently working on
Sub Combined()
Application.DisplayAlerts = False
Const fPath As String = "C:\Users\A9993846\Desktop\"
Dim sh As Worksheet
Dim sName As String
Dim inputString As String
With Application
.Calculation = xlCalculationManual
.EnableEvents = False
.ScreenUpdating = False
End With
sName = Dir(fPath & "*.xls*")
Do Until sName = ""
With GetObject(fPath & sName)
For Each sh In .Worksheets
With sh
.SaveAs Replace(sName, ".xls*", ".txt"), 42 'UPDATE:
End With
Next sh
.Close True
End With
sName = Dir
Loop
With Application
.Calculation = xlAutomatic
.EnableEvents = True
.ScreenUpdating = True
End With
End Sub
But It's not working as expected, I have 0 knowledge on VB. Anyone willing to give a hand?
The code below converts all Excel Workbooks (tests file extension for "xlsx") in a given folder into CSV files. File names will be [workbookname][sheetname].csv, ie "foo.xlsx" will get "foo.xlsxSheet1.scv", "foo.xlsxSheet2.scv", etc. In order to run it, create a plain text file, rename it to .vbs and copy-paste the code below. Change path info and run it.
Option Explicit
Dim oFSO, myFolder
Dim xlCSV
myFolder="C:\your\path\to\excelfiles\"
Set oFSO = CreateObject("Scripting.FileSystemObject")
xlCSV = 6 'Excel CSV format enum
Call ConvertAllExcelFiles(myFolder)
Set oFSO = Nothing
Call MsgBox ("Done!")
Sub ConvertAllExcelFiles(ByVal oFolder)
Dim targetF, oFileList, oFile
Dim oExcel, oWB, oWSH
Set oExcel = CreateObject("Excel.Application")
oExcel.DisplayAlerts = False
Set targetF = oFSO.GetFolder(oFolder)
Set oFileList = targetF.Files
For Each oFile in oFileList
If (Right(oFile.Name, 4) = "xlsx") Then
Set oWB = oExcel.Workbooks.Open(oFile.Path)
For Each oWSH in oWB.Sheets
Call oWSH.SaveAs (oFile.Path & oWSH.Name & ".csv", xlCSV)
Next
Set oWSH = Nothing
Call oWB.Close
Set oWB = Nothing
End If
Next
Call oExcel.Quit
Set oExcel = Nothing
End Sub
You can give better file naming, error handling/etc if needed.
The issue with your code is that you define sPath as a path containing wildcard characters:
sName = Dir(fPath & "*.xls*")
and replace only the extension portion (.xls*), but leave the wildcard character before the extension in place:
Replace(sName, ".xls*", ".txt")
This produces the following path:
C:\Users\A9993846\Desktop\*.txt
which causes the error you observed, because the SaveAs method tries to save the spreadsheet to a file with the literal name *.txt, but * is not a valid character for file names.
Replace this:
.SaveAs Replace(sName, ".xls*", ".txt"), 42
with this:
Set wb = sh.Parent
basename = Replace(wb.FullName, Mid(wb.Name, InStrRev(wb.Name, ".")), "")
.SaveAs basename & "_" & sh.Name & ".txt", xlUnicodeText

Resources