Open Specified Workbooks Only - excel

I run this code daily that will affect each .xlsx workbook in the directory, but how can I ignore the workbook if the file name is not in the "Okay" array?
This is my current syntax:
Option Explicit
Public Sub OpenExcelInDir()
Dim MyFolder As String
Dim MyFile As String
MyFolder = "C:\ExcelSheets"
MyFile = Dir(MyFolder & "\*.xlsx")
Do While MyFile <> ""
Workbooks.Open Filename:=MyFolder & "\" & MyFile
MyFile = Dir
Call UpdateAllSheets
Loop
End Sub
Now I want to alter it so that I can declare a string array and only open the workbooks in the array something like so:
Dim goodWB() As String
goodWB= Split("ABC123,DEF456,GHI789", ",")

Even though I like the IsInArray function I think the algorithm is utterly inefficient. If you have 1000 files in that folder you will create 1000 temp arrays if one of the few given filenames match. Furthermore, I would expect that after opening one of the wanted files the code would not test against this name anymore (which is not the case).
Instead I propose to look at the problem from the other end:
Public Sub OpenExcelInDir()
Dim goodWB, filename
Dim MyFolder As String
Dim MyFile As String
goodWB = Array("ABC123.xls", "DEF456.xlsx", "GHI789.xlsx")
MyFolder = "C:\ExcelSheets"
For Each filename In goodWB
MyFile = MyFolder & "\" & filename
If Len(Dir(MyFile)) > 0 Then
Workbooks.Open filename:=MyFile
Call UpdateAllSheets
End If
Next WB
End Sub
Here, the Dir() function is used to test for the existance of the wanted filename in the specified folder. As an additional advantage there won't be any ambiguities like EEM mentioned in his/her comment.

I think this will do what you are asking for. I added a line to test if the file name matched one in the array.
Tested
Option Explicit
Public Sub OpenExcelInDir()
Dim goodWB() As String
goodWB = Split("ABC123.xlsx,DEF456.xlsx,GHI789.xlsx", ",")
Dim MyFolder As String
Dim MyFile As String
MyFolder = "C:\ExcelSheets"
MyFile = Dir(MyFolder & "\*.xlsx")
Do While MyFile <> ""
If IsInArray(MyFile, goodWB) Then
Workbooks.Open Filename:=MyFolder & "\" & MyFile
MyFile = Dir
Call UpdateAllSheets
End If
MyFile = Dir
Loop
End Sub
Function IsInArray(stringToBeFound As String, arr As Variant) As Boolean
IsInArray = (UBound(Filter(arr, stringToBeFound)) > -1)
End Function

Public Sub OpenExcelInDir()
Const kExt As String = ".xlsm" `As extension is fixed it could be defined as a constant to avoid repetition
Dim aWbks As Variant, vItm As Variant ‘Suggest to define the array in one step choose the form you prefer
‘aWbks = Array("ABC123", "DEF456", "GHI789")
aWbks = [{"ABC123", "DEF456", "GHI789"}]
Dim MyFolder As String
Dim MyFile As String
MyFolder = "C:\ExcelSheets"
MyFile = Dir(MyFolder & "\*" & kExt)
Do While MyFile <> ""
For Each vItm In aWbks
If vItm & kExt = MyFile Then
Workbooks.Open Filename:=MyFolder & "\" & MyFile
Call UpdateAllSheets
Exit For
End If: Next
MyFile = Dir
Loop
End Sub

Related

Opening files from a folder using values stored in a range

I have the following code to open a file that contains a number that is usually ten digits.
I would like the code to refer to my worksheet for that number rather than mentioning it in the code.
When I try the Range formula, it doesn't work because the number is too large to be stored as an integer. If I store this number as text, it's not able to locate the file.
Sub OpenFiles()
Dim MyFolder As String
Dim MyFile As String
MyFolder = "H:\Test\" 'EXACT folder name containing the files.
'Change to suit, but don't forget the trailing backslash '\'
MyFile = Dir(MyFolder & "\*2964179000*.xlsm")
Do Until MyFile = ""
Workbooks.Open Filename:=MyFolder & "" & MyFile
MyFile = Dir
Loop
End Sub
If you need to store long numbers on the sheet then format the cell(s) as Text before adding their content.
You should be able to do something like this:
Sub OpenFiles()
Dim MyFolder As String, ws As Worksheet
Dim MyFile As String
Set ws = ThisWorkbook.Worksheets("Info") 'for example
MyFolder = "H:\Test\"
MyFile = Dir(MyFolder & "*" & ws.Range("A10").Value & "*.xlsm")
Do Until MyFile = ""
Workbooks.Open Filename:=MyFolder & "" & MyFile
MyFile = Dir
Loop
End Sub

Get a filename from a folder using a wildcard

I'm completely new to VBA and had some trouble googling this problem cause variable has multiple meanings.
I am trying to open a file and assign its name to a variable. The file's name is never the same though I always download it to the same folder (one file in that folder only). The only recognizable thing about the file are 3 letters "ABC".
So far I managed to get opening the file to work but not assigning the non-standardized file name to a variable.
Sub openwb()
Dim wb As Workbook Dim directory As String
directory = "D:\Users\AAA\Desktop\Practice"
Set FSO = CreateObject("Scripting.FileSystemObject")
Set folder = FSO.GetFolder(directory)
For Each file In folder.Files
If Mid(file.Name, InStrRev(file.Name, ".") + 1) = "xlsm" Then
Workbooks.Open directory & Application.PathSeparator & file.Name
End If
Next file
End Sub
Public Sub RecordFileName()
Dim sPath As String, sFile As String
Dim wb As Workbook
sPath = "D:\Users\AAA\Desktop\Practice"
sFile = sPath & "*ABC*"
End Sub
Here is a function you can use. It will return the filename you are looking for, and you can specify a file pattern if you want to, or you can omit that argument and it will assume all files.
Function GetFullFileName(sFolder As String, Optional sPattern As String = "*") As String
Dim sFile As String
' ensure sFolder ends with a backslash
If Right$(sFolder, 1) <> "\" Then sFolder = sFolder & "\"
sFile = Dir(sFolder & sPattern)
If sFile = "" Then
MsgBox "NOT FOUND: " & sFolder & sPattern
End
End If
GetFullFileName = sFolder & sFile
End Function
Usage:
MsgBox GetFullFileName("C:\Users\Fred\Documents")
Or
MsgBox GetFullFileName("C:\Users\Fred\Documents\", "*ABC*.xlsm")
Or
sFullFile = GetFullFileName("C:\Users\Fred\Documents\", "*ABC*.xlsm")

Trying to rename a file in a folder (based on a string within the filename)

Hi there I am trying to create a Sub where I find a file in a folder with the name containing a specific phrase like "test_file" and rename it with a different name/extension. I have the following code that doesn't seem to work: (Also I don't know how to search for a specific string within a filename and execute the renaming according to that)
Sub ReName()
Dim myFile As String
Dim myPath As String
Dim mVal As String
mVal = "_12345678_" 'test string'
myPath = "C:\Users\bf91955\Desktop\testfolder\" 'folder path'
myFile = Dir(pathname & "*test_file*") 'real file name is 2222_test_test_file.xlsx'
myFile = myPath & myFile
NewName = "new_test_file & mVal & .xlsx" 'save it as .xlsx and with the new filename including myVal'
Name myFile As myPath & NewName 'rename
End Sub
Any help would be appreciated!
Have a look at the comments you had a couple of errors
Sub ReName()
Dim myFile As String
Dim myPath As String
Dim mVal As String
mVal = "_12345678_" 'test string'
myPath = "C:\Users\bf91955\Desktop\testfolder\" 'folder path'
'' You weren't referencing MyPath here - guessing copy and paste error
myFile = Dir(myPath & "*test_file*") 'real file name is 2222_test_test_file.xlsx'
myFile = myPath & myFile
'' This was passing the variable as part of the string
newname = "new_test_file" & mVal & ".xlsx" 'save it as .xlsx and with the new filename including myVal'
Name myFile As myPath & newname 'rename
End Sub

Loop Through Folders and SubFolders - Multiple Folder Path [duplicate]

I have macro, if I put in cell E1 name of the file, macro search trough C:\Users\Marek\Desktop\Makro\ directory, find it and put the needed values in specific cells of my original file with macro.
Is it possible to make this work without specific folder location? I need something that can search trough C:\Users\Marek\Desktop\Makro\ with many subfolders in it.
My code:
Sub Zila1()
Dim SaveDriveDir As String, MyPath As String
Dim FName As Variant
Dim YrMth As String
SaveDriveDir = CurDir
MyPath = Application.DefaultFilePath 'or use "C:\Data"
ChDrive MyPath
ChDir MyPath
FName = Sheets("Sheet1").Range("E1").Text
If FName = False Then
'do nothing
Else
GetData "C:\Users\Marek\Desktop\Makro\" & FName & ".xls", "Vystupna_kontrola", _
"A16:A17", Sheets("Sheet1").Range("B2:B3"), True, False
GetData "C:\Users\Marek\Desktop\Makro\" & FName & ".xls", "Vystupna_kontrola", _
"AE23:AE24", Sheets("Sheet1").Range("B3:B4"), True, False
GetData "C:\Users\Marek\Desktop\Makro\" & FName & ".xls", "Vystupna_kontrola", _
"AE26:AE27", Sheets("Sheet1").Range("B4:B5"), True, False
GetData "C:\Users\Marek\Desktop\Makro\" & FName & ".xls", "Vystupna_kontrola", _
"AQ59:AQ60", Sheets("Sheet1").Range("B5:B6"), True, False
GetData "C:\Users\Marek\Desktop\Makro\" & FName & ".xls", "Vystupna_kontrola", _
"AR65:AR66", Sheets("Sheet1").Range("B6:B7"), True, False
End If
ChDrive SaveDriveDir
ChDir SaveDriveDir
End Sub
Just for fun, here's a sample with a recursive function which (I hope) should be a bit simpler to understand and to use with your code:
Function Recurse(sPath As String) As String
Dim FSO As New FileSystemObject
Dim myFolder As Folder
Dim mySubFolder As Folder
Set myFolder = FSO.GetFolder(sPath)
For Each mySubFolder In myFolder.SubFolders
Call TestSub(mySubFolder.Path)
Recurse = Recurse(mySubFolder.Path)
Next
End Function
Sub TestR()
Call Recurse("D:\Projets\")
End Sub
Sub TestSub(ByVal s As String)
Debug.Print s
End Sub
Edit: Here's how you can implement this code in your workbook to achieve your objective.
Sub TestSub(ByVal s As String)
Dim FSO As New FileSystemObject
Dim myFolder As Folder
Dim myFile As File
Set myFolder = FSO.GetFolder(s)
For Each myFile In myFolder.Files
If myFile.Name = Range("E1").Value Then
Debug.Print myFile.Name 'Or do whatever you want with the file
End If
Next
End Sub
Here, I just debug the name of the found file, the rest is up to you. ;)
Of course, some would say it's a bit clumsy to call twice the FileSystemObject so you could simply write your code like this (depends on wether you want to compartmentalize or not):
Function Recurse(sPath As String) As String
Dim FSO As New FileSystemObject
Dim myFolder As Folder
Dim mySubFolder As Folder
Dim myFile As File
Set myFolder = FSO.GetFolder(sPath)
For Each mySubFolder In myFolder.SubFolders
For Each myFile In mySubFolder.Files
If myFile.Name = Range("E1").Value Then
Debug.Print myFile.Name & " in " & myFile.Path 'Or do whatever you want with the file
Exit For
End If
Next
Recurse = Recurse(mySubFolder.Path)
Next
End Function
Sub TestR()
Call Recurse("D:\Projets\")
End Sub
This sub will populate a Collection with all files matching the filename or pattern you pass in.
Sub GetFiles(StartFolder As String, Pattern As String, _
DoSubfolders As Boolean, ByRef colFiles As Collection)
Dim f As String, sf As String, subF As New Collection, s
If Right(StartFolder, 1) <> "\" Then StartFolder = StartFolder & "\"
f = Dir(StartFolder & Pattern)
Do While Len(f) > 0
colFiles.Add StartFolder & f
f = Dir()
Loop
If DoSubfolders then
sf = Dir(StartFolder, vbDirectory)
Do While Len(sf) > 0
If sf <> "." And sf <> ".." Then
If (GetAttr(StartFolder & sf) And vbDirectory) <> 0 Then
subF.Add StartFolder & sf
End If
End If
sf = Dir()
Loop
For Each s In subF
GetFiles CStr(s), Pattern, True, colFiles
Next s
End If
End Sub
Usage:
Dim colFiles As New Collection
GetFiles "C:\Users\Marek\Desktop\Makro\", FName & ".xls", True, colFiles
If colFiles.Count > 0 Then
'work with found files
End If
If this helps, you can also use FileSystemObject to retrieve all subfolders of a folder.
You need to check the reference "Microsot Scripting Runtime" to get Intellisense and use the "new" keyword.
Sub GetSubFolders()
Dim fso As New FileSystemObject
Dim f As Folder, sf As Folder
Set f = fso.GetFolder("D:\Proj\")
For Each sf In f.SubFolders
'Code inside
Next
End Sub
I actually just found this today for something I'm working on. This will return file paths for all files in a folder and its subfolders.
Dim colFiles As New Collection
RecursiveDir colFiles, "C:\Users\Marek\Desktop\Makro\", "*.*", True
Dim vFile As Variant
For Each vFile In colFiles
'file operation here or store file name/path in a string array for use later in the script
filepath(n) = vFile
filename = fso.GetFileName(vFile) 'If you want the filename without full path
n=n+1
Next vFile
'These two functions are required
Public Function RecursiveDir(colFiles As Collection, strFolder As String, strFileSpec As String, bIncludeSubfolders As Boolean)
Dim strTemp As String
Dim colFolders As New Collection
Dim vFolderName As Variant
strFolder = TrailingSlash(strFolder)
strTemp = Dir(strFolder & strFileSpec)
Do While strTemp <> vbNullString
colFiles.Add strFolder & strTemp
strTemp = Dir
Loop
If bIncludeSubfolders Then
strTemp = Dir(strFolder, vbDirectory)
Do While strTemp <> vbNullString
If (strTemp <> ".") And (strTemp <> "..") Then
If (GetAttr(strFolder & strTemp) And vbDirectory) <> 0 Then
colFolders.Add strTemp
End If
End If
strTemp = Dir
Loop
'Call RecursiveDir for each subfolder in colFolders
For Each vFolderName In colFolders
Call RecursiveDir(colFiles, strFolder & vFolderName, strFileSpec, True)
Next vFolderName
End If
End Function
Public Function TrailingSlash(strFolder As String) As String
If Len(strFolder) > 0 Then
If Right(strFolder, 1) = "\" Then
TrailingSlash = strFolder
Else
TrailingSlash = strFolder & "\"
End If
End If
End Function
This is adapted from a post by Ammara Digital Image Solutions.(http://www.ammara.com/access_image_faq/recursive_folder_search.html).

Access VBA Import Specific Excel Files from different subfolders

I have a problem that I can't find the right code to do it.
So I have a Main Folder (C:\Products) with multiple subfolders that correspond to different the products (C:\Products\Chocolates , C:\Products\Milk and many more).
Each subfolder have many excel files but I just want to import the one that is named sells.xlxs. Each subfolder have a sells.xlxs and I Want to import all sells.xlxs to an access Database.
EDIT: Sorry I didn't Upload the code I was using:
Sub Insert2()
Const cstrSheetName As String = "Weekly"
Dim strDir As String
Dim strFile As String
Dim strTableName As String
Dim MyPath As String
Dim i As Long
i = 0
MyPath = "C:\Products"
strTableName = "Sells"
If Left(MyPath, 1) <> "\" Then
strDir = MyPath & "\"
Else
strDir = MyPath
End If
strFile = Dir(MyPath & "\Sells.XLSX")
While strFile <> ""
i = i + 1
strFile = strDir & strFile
Debug.Print "importing " & strFile
DoCmd.TransferSpreadsheet _
TransferType:=acImport, _
SpreadsheetType:=acSpreadsheetTypeExcel9, _
TableName:=strTableName, _
FileName:=strFile, _
HasFieldNames:=True, _
Range:=cstrSheetName & "$"
strFile = Dir()
Wend
End Sub
Do you think you can help me?
Many thanks
Dim FileSystem As Object
Dim HostFolder As String
HostFolder = MyPath
Set FileSystem = CreateObject("Scripting.FileSystemObject")
DoFolder FileSystem.GetFolder(HostFolder)
Sub DoFolder(Folder)
Dim SubFolder
For Each SubFolder In Folder.SubFolders
Dim File
For Each File In Folder.Files
' Operate on each file
Next
Next
End Sub
Code credit to Rich, rearranged code so it doesn't recursively iterate all subfolders, just the subfolders of MyPath

Resources